阿里巴巴的深度学习前向推理库MNN中使用了一个图像库stb,github地址是https://github.com/nothings/stb
,这个库包含一堆.h头文件,如果你想要对图片进行简单操作(如:将图像数据载入内存、进行缩放、图像保存等),又不想因为这些简单操作,引入opencv等大库,那stb将是一个好选择。
- 图像载入
载入图像使用的是stb_image.h头文件,支持的图像文件格式有:JPEG、PNG、TGA、BMP、PSD、GIF、HDR、PIC、PNM。使用的函数是stbi_load(图像文件名, 获取图像宽,获取图像高, 获取图像通道数, 指定期望的通道数)。
int x, y, channels_in_file, desired_channels = 3;
unsigned char* data = stbi_load(image.c_str(), &x, &y, &channels_in_file, desired_channels);
free(data);
- 图像缩放
图像缩放使用的是stb_image_resize.h头文件,使用的函数是stbir_resize_uint8(输入图像数据指针,输入图像宽,输入图像高,输入图像步长,输出图像数据指针,输出图像宽,输出图像高,输出图像步长,图像通道数)。
int width_resize = x * 1.5, height_resize = y * 1.4;
unsigned char* output_pixels = (unsigned char*)malloc(width_resize * height_resize * desired_channels);
int ret = stbir_resize_uint8(data, x, y, 0, output_pixels, width_resize, height_resize, 0, desired_channels);
free(output_pixels);
- 图像保存
图像保存使用的是stb_image_write.h头文件,使用的函数是stbi_write_xxx(保存图像名,图像宽,图像高,图像通道数,图像数据指针,步长,图像质量),xxx是图像文件格式,如png、bmp、tga、hdr、jpg。
const std::string save_name_png = image + ".png";
const std::string save_name_jpg = image + ".jpg";
ret = stbi_write_png(save_name_png.c_str(), width_resize, height_resize, desired_channels, output_pixels, 0);
if (ret == 0) {
fprintf(stderr, "fail to write image png: %s\n", image.c_str());
return -1;
}
ret = stbi_write_jpg(save_name_jpg.c_str(), width_resize, height_resize, desired_channels, output_pixels, 90);
if (ret == 0) {
fprintf(stderr, "fail to write image jpg: %s\n", image.c_str());
return -1;
}
网友评论