如何在C/C++中将灰度JPEG图像文件读入到一个二维数组中?
stb_image
和stb_image_write
,可以在这里找到。stb_image.h
和stb_image_write.h
放在您的文件夹中即可。#include <stdint.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
int main() {
int width, height, bpp;
uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);
stbi_image_free(rgb_image);
return 0;
}
这里是编写图像的代码:
#include <stdint.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define CHANNEL_NUM 3
int main() {
int width = 800;
int height = 800;
uint8_t* rgb_image;
rgb_image = malloc(width*height*CHANNEL_NUM);
// Write your code to populate rgb_image here
stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);
return 0;
}
您可以不使用标志或依赖项进行编译:
g++ main.cpp
其他轻量级的替代方案包括:
请查看英特尔开放CV库...
Corona 很不错。来自教程:
corona::Image* image = corona::OpenImage("img.jpg", corona::PF_R8G8B8A8);
if (!image) {
// error!
}
int width = image->getWidth();
int height = image->getHeight();
void* pixels = image->getPixels();
// we're guaranteed that the first eight bits of every pixel is red,
// the next eight bits is green, and so on...
typedef unsigned char byte;
byte* p = (byte*)pixels;
for (int i = 0; i < width * height; ++i) {
byte red = *p++;
byte green = *p++;
byte blue = *p++;
byte alpha = *p++;
}
像素将是一个一维数组,但您可以轻松地将给定的x和y位置转换为1D数组中的位置。类似于pos =(y * width)+ x