记录一下图像转格式的代码,方便下次查阅:
同事转换图像和保存图像的代码:
void Rgb2Gray(unsigned char* rgb_data, unsigned char* gray_data, int width, int height)
{
unsigned int gray_sum = 0;
int i = 0;
int j = 0;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
*gray_data++ = (28 * (*(rgb_data + 2)) + 151 * (*(rgb_data + 1)) + 77 * (*rgb_data)) >> 8;
*gray_data++ = (28 * (*(rgb_data + 2)) + 151 * (*(rgb_data + 1)) + 77 * (*rgb_data)) >> 8;
*gray_data++ = (28 * (*(rgb_data + 2)) + 151 * (*(rgb_data + 1)) + 77 * (*rgb_data)) >> 8;
rgb_data += 3;
}
}
}
void Save2File(unsigned char* file_buffer, unsigned long buffer_size, int width, int height, unsigned int frame_index, std::string imgformat)
{
if (!file_buffer)
{
TRACK_LOG(LOG_ERROR, "param error, pBuffer:%p, size:%d\n", file_buffer, buffer_size);
return;
}
char fileName[250] = { 0 };
time_t tt = time(0);
struct tm* tmv = localtime(&tt);
snprintf(fileName, sizeof(fileName), "C:\\temp\\%04d-%02d-%02d_%02d-%02d-%02d-%dx%d_%03d.%s",tmv->tm_year + 1900, tmv->tm_mon + 1, tmv->tm_mday, tmv->tm_hour, tmv->tm_min, tmv->tm_sec, width, height, frame_index, imgformat.c_str());
TRACK_LOG(LOG_INFO, "filename: %s, buffer:%p, dataLen:%lu\n", fileName, file_buffer, buffer_size);
FILE* fp = fopen(fileName, "wb+");
if (fp)
{
fwrite(file_buffer, 1, buffer_size, fp);
fflush(fp);
fclose(fp);
fp = NULL;
}
}
同事使用的C++,我这边无法直接查看,所以更换图像的格式:
代码:
#filename = os.path.join(img_dir, file)
binFile = open('2022-12-27_14-41-23-1920x1080_037.rgb', "rb")
data = binFile.read()
data = [int(x) for x in data]
# 图像尺寸是需要预先知道的
empty_img = np.array(data).reshape((1080, 1920, 3)).astype(np.uint8)
save_path = os.path.join(save_dir, file[:-4]+'.jpg')
cv2.imwrite(save_path, empty_img)