#include <iostream>
#include <cmath>
using namespace std;
void scanRaw(unsigned char* in, FILE* input);
void printRaw(unsigned char* out, FILE* output);
void bits_resolution(unsigned char* in, unsigned char* out);
#define width 256
#define height 256
void main()
{
//////////////////////// variables
////////// file
FILE* Input = fopen("LENA_256x256_1ch.raw", "rb");
FILE* Output = fopen("lena_7bits_256x256_1ch.raw", "wb");
////////// 배열 선언
unsigned char* in = new unsigned char[width*height];
unsigned char* out = new unsigned char[width*height];
memset(in, 0, width*height*sizeof(unsigned char));
memset(out, 0, width*height*sizeof(unsigned char));
////////// scan original image
scanRaw(in, Input);
////////// scan original image
bits_resolution(in, out);
////////// result
printRaw(out, Output);
////////// delete memory
delete[] in;
delete[] out;
fcloseall();
}
////////// scan raw
void scanRaw(unsigned char* in, FILE* input)
{
int row, col;
for (row = 0; row < height; row++)
{
for (col = 0; col < width; col++)
fscanf(input, "%c", &in[width*row+col]);
}
}
////////// print raw
void printRaw(unsigned char* out, FILE* output)
{
int row, col;
for (row = 0; row < height; row++)
{
for (col = 0; col < width; col++)
fprintf(output, "%c", out[width*row+col]);
}
}
////////// bits resolution
void bits_resolution(unsigned char* in, unsigned char* out)
{
int row, col;
////////// 원하는 bits 선택
int bit=7;
//////////
int x = 256/(pow(2, bit)-1);
for (row = 0; row < height; row++)
{
for (col = 0; col < width; col++)
{
if(in[width*row+col]%x <= x/2)
out[width*row+col] = in[width*row+col] - in[width*row+col]%x;
else if(in[width*row+col]%x > x/2)
{
if(in[width*row+col] + x - in[width*row+col]%x > 255)
out[width*row+col] = 255;
else
out[width*row+col] = in[width*row+col] + x - in[width*row+col]%x;
}
}
}
}