我想知道如何访问像素值和Floodfill 。在程序执行时,它会找到白色和黑色像素,但在应用floodfill函数时,最终结果是-all灰色图像。我想要做的是:
int best_resut = 0;
Point best = (0,0);
for(int i = 0; i < img_bin.rows; i++)
{
for(int j = 0; j < img_bin.cols; j++)
{
Vec3b intensity = img_bin.at<uchar>(i, j);
uchar color = intensity.val[0];
printf("Looking (%d,%d) Value %d\n", i, j, color);
if(color==255)
{
printf("White Pixel\n");
Point sp = (i, j);
int current_result = floodFill(img_bin, sp, 128);
if (current_result > best_result)
{
best_result = current_result;
best = Point (i,j);
floodFill(img_bin,sp, 255);
}
else
{
floodFill(img_bin, sp, 255);
}
}
}
}
namedWindow("final",CV_WINDOW_AUTOSIZE);
imshow("final", img_bin);
答案 0 :(得分:1)
假设您的图像是3通道彩色图像
Vec3b intensity = img_bin.at<uchar>(i, j);
应该是
Vec3b intensity = img_bin.at<Vec3b>(i, j);
由于Point接受(x,y)参数,它应该是Point sp = (j, i);
,而不是Point sp = (i, j);
正确的代码:
int best_result = 0;
cv::Point best = (0,0);
cv::Vec3b white(255, 255, 255);
for(int i = 0; i < img_bin.rows; i++)
{
cv::Vec3b* img_row = img_bin.ptr<cv::Vec3b>(i);
for(int j = 0; j < img_bin.cols; j++)
{
cv::Vec3b pixel = img_row[j];
printf("Looking (%d,%d) Value %d %d %d\n", j, i, pixel[2], pixel[1], pixel[0]);
if(pixel == white)
{
printf("White Pixel\n");
cv::Point sp(j, i);
int current_result = cv::floodFill(img_bin, sp, cv::Scalar(128, 128, 128));
if (current_result > best_result)
{
best_result = current_result;
best = sp;
}
cv::floodFill(img_bin, sp, cv::Scalar(255, 255, 255));
}
}
}
cv::namedWindow("final",CV_WINDOW_AUTOSIZE);
cv::imshow("final", img_bin);
cv::waitKey(0);