刚开始接触到OpenCV,本身是想学借助OpenCV的库来进行图像处理学习的,后来发现OpenCV将所有的东西都集成起来了,对于打算学习图像处理来说这样反而不是什么好事;
在我看来,图像处理基本基于对像素值的处理,那么我们尽可能的用数组来存储像素值,对于OpenCV来说不便于按照我们的做法来对图片进行处理。但是OpenCV给我们集成了cv::Mat::at这样一个结构,用于读取图片的像素值,那么我们就可以使用它来将像素值存储在数组中了。
image.at<Vec3b>(row, col)[i]可以读取到图片中的像素值,row为行、col为列、i为RGB的第几通道。
for (int row = 0; row < image.rows; row++) //行
{
for (int col = 0; col < image.cols; col++) //列
{
for (int i = 0; i < 3; i++)
{
str[row * 400 * 3 + col * 3 + i] = image.at<Vec3b>(row, col)[i];
}
}
}
这样我们就可以将image图片中的像素值保存到str数组中,我们采用的是三通道RGB图片,在数组中的存储顺序是B,G,R。
但是这里有个缺陷就是我们需要首先数组的长度,那么就意味着对应的图片长宽是固定的。
对于之后的图像显示,我仍然使用了能被openCV处理的Mat格式图像数据,就是对指向图像的指针生成Mat格式的图像数据。
int fnCameraCheckA(unsigned char* imageData, int width, int height, int *result1)
{
Mat img(height, width, CV_8UC3, imageData); //CV_8UC3:8位无符号的三通道---RGB彩色图像
if (!img.data)
{
printf(" No image data \n ");
return -1;
}
imshow("传递过来的图像", img);
*result1 = 1;
return 1;
}
这样我们就可以随意的对图片进行处理,并借助OpenCV强大的底层库进行其他操作。
#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cstring>
using namespace cv;
int fnCameraCheckA(unsigned char* imageData, int width, int height, int * result);
int main(int argc, char** argv)
{
const char* imageName = "test_2.bmp";
Mat image;
image = imread(imageName); //读图片
char str[400 * 400 * 3];
for (int row = 0; row < image.rows; row++) //行
{
for (int col = 0; col < image.cols; col++) //列
{
for (int i = 0; i < 3; i++)
{
str[row * 400 * 3 + col * 3 + i] = image.at<Vec3b>(row, col)[i];
}
}
}
char* imgData = str;
imshow("原图", image);
int width, height;
int a = -1;
int *result1 = &a; //判断是否传递成功
width = image.cols; // 列数
height = image.rows; // 行数
// 利用传递过来的图像指针和行列参数,生成能被openCV处理的Mat格式图像数据
fnCameraCheckA((unsigned char*)imgData, width, height, result1);
if (*result1 == 1)
{
printf("图像传递successful!!");
}
waitKey(0);
return 0;
}
int fnCameraCheckA(unsigned char* imageData, int width, int height, int *result1)
{
Mat img(height, width, CV_8UC3, imageData); //CV_8UC3:8位无符号的三通道---RGB彩色图像
if (!img.data)
{
printf(" No image data \n ");
return -1;
}
imshow("传递过来的图像", img);
*result1 = 1;
return 1;
}