Created
December 12, 2013 16:49
-
-
Save mahiuchun/7931161 to your computer and use it in GitHub Desktop.
img2bin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string> | |
#include <opencv2/opencv.hpp> | |
int main(int argc, const char * argv[]) | |
{ | |
if (argc < 2) { | |
fprintf(stderr, "Usage: img2bin image-file\n"); | |
exit(1); | |
} | |
cv::Mat img = cv::imread(argv[1]); | |
if (img.type() != CV_8UC3) { | |
fprintf(stderr, "Error: wrong image type\n"); | |
exit(1); | |
} | |
std::string filename(argv[1]); | |
const size_t last_slash_idx = filename.find_last_of("\\/"); | |
if (std::string::npos != last_slash_idx) | |
{ | |
filename.erase(0, last_slash_idx + 1); | |
} | |
const size_t period_idx = filename.rfind('.'); | |
if (std::string::npos != period_idx) | |
{ | |
filename.erase(period_idx); | |
} | |
filename.append(".inc"); | |
FILE *fp = fopen(filename.c_str(), "w"); | |
for (int i = 0; i < img.rows; i++) | |
{ | |
fprintf(fp, "dw"); | |
for(int j = 0; j < img.cols; j++) | |
{ | |
cv::Vec3b bgrPixel = img.at<cv::Vec3b>(i, j); | |
unsigned char r = bgrPixel.val[2]; | |
unsigned char g = bgrPixel.val[1]; | |
unsigned char b = bgrPixel.val[0]; | |
unsigned short word = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); | |
if (j == 0) { | |
fprintf(fp, " %d", word); | |
} else { | |
fprintf(fp, ", %d", word); | |
} | |
} | |
fprintf(fp, "\n"); | |
} | |
fclose(fp); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment