我正在尝试将较小的图像复制到较大的图像。我这样做时会出错。我不想使用ROI方法,因为我将使用此代码进行多次迭代,并且每次为图像选择ROI都不有效,并且ROI每次都会改变。我不想使用copyTo()
功能复制图像,因为下一步是检查图像像素是否为0(即黑色),如果不是,则不进行复制。我可以读取像素的值,但是当我尝试将其复制到另一张图像时出现错误。我研究了以前的所有文章,并尝试进行更改,但是没有一个起作用。我将附加我的代码以及我收到的错误。
#includeusing namespace cv; int main() { Mat img1, img2, output; img1 = imread("E:/Image2.jpg", 1); img2 = imread("E:/Marker2.PNG", 1); int startrow, startcol; startrow = 20; startcol = 20; int rows, cols,i,j,r=1,c; cv::Size s = img2.size(); rows = s.height; cols = s.width; for (i = startrow; i <= startrow + rows; i++) { c = 1; for (j = startcol; j <= startcol + cols; j++) { output.at (i, j) = img2.at (r, c); c++; } r++; } imshow("Output", output); waitKey(1000); return 0; }
非常感谢您的帮助。
不要使用复杂的像素位置参数。而是仅使用ROI中的子图像:
cv::Mat input = cv::imread("../inputData/Lenna.png"); cv::Mat output = input.clone(); cv::Mat marker = cv::imread("../inputData/marker.png"); // subimage dimensions: cv::Point startPosition = cv::Point(20,20); cv::Size size = marker.size(); // ROI: cv::Rect subImageRect = cv::Rect(startPosition, size); // limit the roi if roi is bigger than the original image: cv::Rect fullImageRect = cv::Rect(cv::Point(0,0), input.size()); // intersection of both rois subImageRect = subImageRect & fullImageRect; if(subImageRect.width == 0 || subImageRect.height == 0) { std::cout << "marker position isn't within the image dimensions" << std::endl; return 0; } // subimage = reference to image part of original image: cv::Mat outputSubImage = output(subImageRect); // marker subimage should be the whole marker, but might be reduced. cv::Mat markerSubImage = marker(cv::Rect(0,0,subImageRect.width, subImageRect.height)); // now just copy the data: markerSubImage.copyTo(outputSubImage); // if you don't want to use .copyTo, just use a loop over 0 .. subImage.width/height and copy from same pixel location to same pixel location. cv::imshow("output", output); cv::waitKey(0);
使用此输入图像:
和这个标记图片:
它生成以下输出:
如果您确定标记在图像中,则可以删除完整性检查以简化代码:
cv::Mat input = cv::imread("../inputData/Lenna.png"); cv::Mat output = input.clone(); cv::Mat marker = cv::imread("../inputData/marker.png"); // subimage dimensions: cv::Point startPosition = cv::Point(20,20); cv::Size size = marker.size(); // ROI: cv::Rect subImageRect = cv::Rect(startPosition, size); // subimage = reference to image part of original image: cv::Mat outputSubImage = output(subImageRect); // now just copy the data: marker.copyTo(outputSubImage); // if you don't want to use .copyTo, just use a loop over 0 .. subImage.width/height and copy from same pixel location to same pixel location.