gpt4 book ai didi

c++ - 如何使用opencv有效地在RGB图像中做复杂的阈值?

转载 作者:太空宇宙 更新时间:2023-11-03 22:25:26 24 4
gpt4 key购买 nike

我想将 matlab 代码翻译成 c++ opencv,它对 RGB 图像进行阈值处理:红色值>阈值 1 和红色/绿色>阈值 2 和红色/蓝色>阈值 3

matlab代码为:

bw=(im(:,:,1)>=red_th&(im(:,:,1)./im(:,:,2))>=red_green_th&(im(:,:,1)./im(:,:,3))>=red_blue_th);

其中 im(:,:,1), im(:,:,2)im(:,:,3) 是 r, g, b值分别。

我发现与使用“for cols and for rows”循环所有像素相比,matlab 代码非常有效。因此,我想在 opencv 中找到类似的有效方法,而不是循环列和行。

看了一些关于cv::threshold和inRange的资料,但是好像不能满足我的要求。

最佳答案

您不能直接使用 thresholdinRange 执行此操作,但您可以轻松地将其转换为 OpenCV,首先拆分 3 个 channel ,然后使用矩阵表达式:

Mat im = ...
vector<Mat> planes;
split(im, planes); // B, G, R planes

Mat bw = (planes[2] >= red_th) &
(planes[2] / planes[1] >= red_green_th) &
(planes[2] / planes[0] >= red_blue_th);

由于 Matlab 通常处理 double ,您最好将 OpenCV 矩阵转换为 double (除非它们已经是 double ):

Mat im = ...
vector<Mat> planes;
split(im, planes); // B, G, R planes

for(size_t i=0; i<planes.size(); ++i) {
planes[i].convertTo(planes[i], CV_64F);
}

Mat bw = (planes[2] >= red_th) &
(planes[2] / planes[1] >= red_green_th) &
(planes[2] / planes[0] >= red_blue_th);

或者您可以使用 for 循环,如果您处理指针(我假设您的 imCV_8UC3 类型),它会非常快:

Mat3b im = ...
Mat1b bw(im.rows, im.cols, uchar(0));

int rows = im.rows;
int cols = im.cols;
if(im.isContinuous()) {
cols = rows * cols;
rows = 1;
}

for(int r=0; r<rows; ++r) {
Vec3b* ptr_im = im.ptr<Vec3b>(r);
uchar* ptr_bw = bw.ptr<uchar>(r)
for(int c=0; c<cols; ++c) {
const Vec3b& bgr = ptr_im[c];

// Take care of division by 0

ptr_bw[c] = (bgr[2] >= red_th) &&
(bgr[2] / bgr[1] >= red_green_th) &&
(bgr[2] / bgr[0] >= red_blue_th);
}
}

关于c++ - 如何使用opencv有效地在RGB图像中做复杂的阈值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40845532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com