在opencv中用cv :: rect提取roi

时间:2014-07-16 11:31:49

标签: opencv vector rect roi

我正在尝试提取100x100像素图像的第一个四分之一。我正在考虑使用roi-definition中的cv :: rect函数(参见下面的代码示例)。此外,我的原始图像是矢量数组的一部分(在下面的代码示例中,我只使用一个图像 - 稍后会有几个但这可能与此处的示例无关。)

我所观察到的是一种奇怪的行为:新创建的图像"测试"在大约一半的行之前似乎没问题。然后它显示完全随机的像素(参见示例图像)。

原因是什么?

图像描述:左:orig 100x100图像/右:创建"测试"有错误的图片......

left: orig 100x100 image  / right: created "Test" image with errors...

std::vector<cv::Mat> Image(1);   // create vector array of one 100x100 pixel image
Image[0] = cv::imread(argv[1]);  // or in iOS:  Image[0] = [in_image CVMat];
cv::Rect roi1 = cv::Rect(0, 0, Image[0].cols/2, Image[0].rows/2);
cv::Mat Test = Image[0](roi1);   
imshow("final_result", Test);    // the Test image has error rows !!!!!!! Why ????????

另一个例子: 第二个示例显示左侧的原始150x150像素图像。矩形rect1是100x100pixel。再次 - 同样的问题:裁剪后的图像在开始时显示出良好的性能。但是从某一行开始,像素变得混乱(在这个例子中,它们变成全黑......)。以下是原始的iOS代码。可能是什么问题呢 ??? (我正在使用iOS模拟器 - 这可能是问题吗?

示例代码2:

UIImage *in_image = [UIImage imageNamed:@"image013.jpg"];    // 150 x 150 pixel image
cv::Mat cv_in_image = [in_image CVMat];

NSLog(@"cv_in_image cols = %i", cv_in_image.cols);
NSLog(@"cv_in_image rows = %i", cv_in_image.rows);

cv::Rect rect1;
rect1.x = 28;
rect1.y = 27;
rect1.width = 100;
rect1.height = 100;

NSLog(@"rect1 x = %i", rect1.x);
NSLog(@"rect1 y = %i", rect1.y);
NSLog(@"rect1 width = %i", rect1.width);
NSLog(@"rect1 height = %i", rect1.height);

cv::Mat Image1 = cv_in_image(rect1);

NSLog(@"Image1 cols = %i", Image1.cols);
NSLog(@"Image1 rows = %i", Image1.rows);

self.imageView0.image = [[UIImage alloc] UIImageFromCVMat:(Image1)];

NSLog sais:

cv_in_image cols = 150
cv_in_image rows = 150
rect1 x = 28
rect1 y = 27
rect1 width = 100
rect1 height = 100
Image1 cols = 100
Image1 rows = 100

示例2:左侧图像:右侧150x150像素/矩形(图像1)显示错误!! 在这里,您可以找到example2中的原始图像:link enter image description here

1 个答案:

答案 0 :(得分:3)

我终于找到了解决这个问题的方法:

- &GT;使用函数“cvtColor”

UIImage *in_image = [UIImage imageNamed:@"image013.jpg"];    // 150 x 150 pixel image
cv::Mat cv_in_image = [in_image CVMat];

NSLog(@"cv_in_image cols = %i", cv_in_image.cols);
NSLog(@"cv_in_image rows = %i", cv_in_image.rows);

cv::Rect rect1;
rect1.x = 28;
rect1.y = 27;
rect1.width = 100;
rect1.height = 100;

NSLog(@"rect1 x = %i", rect1.x);
NSLog(@"rect1 y = %i", rect1.y);
NSLog(@"rect1 width = %i", rect1.width);
NSLog(@"rect1 height = %i", rect1.height);

cv::Mat Image1 = cv_in_image(rect1);

// This is the workarround !!!!!!!!!!!
/  -----------------------------------
// Use cvtColor-function twice in a row...
cv::cvtColor(Image1, Image1, cv::COLOR_RGB2BGR);  // after that function, the error is gone
cv::cvtColor(Image1, Image1, cv::COLOR_BGR2RGB);  // I use the function a second time to get back the original color-set...

NSLog(@"Image1 cols = %i", Image1.cols);
NSLog(@"Image1 rows = %i", Image1.rows);

self.imageView0.image = [[UIImage alloc] UIImageFromCVMat:(Image1)];

最终可以创建ROI,如下面的图像文档中所示: (...真的不确定为什么这会突然与iOS中的UIImage-View一起工作!! ????) enter image description here