ISP/sim/software/demosaic.cpp

125 lines
4.1 KiB
C++

#include <fstream>
#include <iostream>
#include <vector>
#include "bmp.hpp"
const int IN_WIDTH = 1920;
const int IN_HEIGHT = 1080;
const int IN_SIZE = IN_WIDTH * IN_HEIGHT;
const int OUT_WIDTH = 1280;
const int OUT_HEIGHT = 720;
const int OUT_SIZE = OUT_WIDTH * OUT_HEIGHT;
const int RAW_TYPE = 1;
const int COLOR_DEPTH = 10;
int main() {
std::ifstream in_image;
in_image.open("./test.RAW", std::ios::in | std::ios::binary);
auto image = std::vector<std::vector<uint16_t>>(
IN_HEIGHT, std::vector<uint16_t>(IN_WIDTH, 0));
for (int y = 0; y < IN_HEIGHT; y++)
for (int x = 0; x < IN_WIDTH; x++) {
uint8_t buf[2] = {0};
in_image.read((char*)buf, sizeof(buf));
image[y][x] = buf[0] + ((uint16_t)buf[1] << 8);
}
int raw_type = RAW_TYPE;
uint8_t* data =
new uint8_t[OUT_WIDTH * OUT_HEIGHT * 3]; // RGB24格式像素数据
for (int32_t y = 0; y < OUT_HEIGHT; ++y) {
for (int32_t x = 0; x < OUT_WIDTH; ++x) {
int32_t index = (y * OUT_WIDTH + x) * 3;
uint16_t red = 0, green = 0, blue = 0;
uint16_t data_cache[3][3] = {
{image[y][x], image[y][x + 1], image[y][x + 2]},
{image[y + 1][x], image[y + 1][x + 1], image[y + 1][x + 2]},
{image[y + 2][x], image[y + 2][x + 1], image[y + 2][x + 2]},
};
switch (raw_type) {
case 0: // Missing B, R on G
blue = (data_cache[1][0] + data_cache[1][2]) / 2;
red = (data_cache[0][1] + data_cache[2][1]) / 2;
green = data_cache[1][1];
break;
case 1: // Missing G, R on B
green = (data_cache[0][1] + data_cache[1][0] +
data_cache[1][2] + data_cache[2][1]) /
4;
red = (data_cache[0][0] + data_cache[0][2] +
data_cache[2][0] + data_cache[2][2]) /
4;
blue = data_cache[1][1];
break;
case 2: // Missing G, B on R
green = (data_cache[0][1] + data_cache[1][0] +
data_cache[1][2] + data_cache[2][1]) /
4;
blue = (data_cache[0][0] + data_cache[0][2] +
data_cache[2][0] + data_cache[2][2]) /
4;
red = data_cache[1][1];
break;
case 3: // Missing B, R on G
red = (data_cache[1][0] + data_cache[1][2]) / 2;
blue = (data_cache[0][1] + data_cache[2][1]) / 2;
green = data_cache[1][1];
break;
}
printf("x=%4d, y=%4d, red=0x%03x, green=0x%03x, blue=0x%03x, raw_type=%d\n", x,
y, red, green, blue, raw_type);
switch (raw_type) {
case 0:
raw_type = 1;
break;
case 1:
raw_type = 0;
break;
case 2:
raw_type = 3;
break;
case 3:
raw_type = 2;
break;
}
data[index + 0] = red >> (COLOR_DEPTH - 8); // R
data[index + 1] = green >> (COLOR_DEPTH - 8); // G
data[index + 2] = blue >> (COLOR_DEPTH - 8); // B
}
if (y % 2) {
raw_type = RAW_TYPE;
} else {
switch (RAW_TYPE) {
case 0:
raw_type = 2;
break;
case 1:
raw_type = 3;
break;
case 2:
raw_type = 0;
break;
case 3:
raw_type = 1;
break;
}
}
}
write_bmp("test.bmp", data, OUT_WIDTH, OUT_HEIGHT);
delete[] data;
return 0;
}