我正在尝试按从最低到最高的顺序对图像(例如 80x20)的像素值进行排序。
下面是一些代码:
bool sortPixel(int first, int second)
{
return (first < second);
}
vector<int>vect_sortPixel;
for(int y=0; y<height; y++)
{
for(int x=0; x<width; x++)
{
vect_sortPixel.push_back(cvGetReal2D(srcImg, y, x));
sort(vect_sortPixel.begin(), vect_sortPixel.end(), sortPixel);
}
}
但是计算需要相当长的时间。有什么减少处理时间的建议吗? 谢谢。
最佳答案
不要使用 getReal2D。速度相当慢。
将图像转换为 cv::Mat 或 Mat。使用其数据指针来获取像素值。 Mat.data() 将为您提供指向原始矩阵的指针。用那个。
就排序而言,我建议您首先创建所有像素的数组,然后使用合并排序对其进行排序(时间复杂度 O(n log n))
#include<opencv2/highgui/highgui.hpp>
#include<stdio.h>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("filename.jpg",CV_LOAD_IMAGE_COLOR);
unsigned char *input = (unsigned char*)(img.data);
int i,j,r,g,b;
for(int i = 0;i < img.cols;i++){
for(int j = 0;j < img.rows;j++){
b = input[img.cols * j + i] ;
g = input[img.cols * j+ i + 1];
r = input[img.cols *j + i +2];
}
}
return 0;
}
使用它,您可以从主矩阵访问像素值。
警告:这不是您比较的方式。我建议通过使用类似的东西,您可以访问像素值。
Mat.data() 为您提供指向原始矩阵的指针。该矩阵是一个一维矩阵,包含所有给定的像素值。
图像 => (x,y,z),(x1,y1,z1) 等..
Mat(原始矩阵) => x,y,z,x1,y1,z1,...
如果您对如何从 Mat 中提取数据仍有疑问,请访问此链接 OpenCV get pixel channel value from Mat image
这是关于合并排序的链接 http://www.cplusplus.happycodings.com/Algorithms/code17.html
关于c++ - 如何改进 cvMat 中的像素排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166760/