用openCv C++复制图像的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15529365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
copy a part of image with openCv c++
提问by Wadii Slatnia
I am using opencv and I want to create an image from a part of another image.
我正在使用 opencv,我想从另一个图像的一部分创建一个图像。
I didn't find a function that do that so I try to implement my Idea which consist of copying the image pixel by pixel but in vain I didn't get the result I am waiting for.
我没有找到这样做的函数,所以我尝试实现我的想法,它包括逐个像素地复制图像,但徒劳无功,我没有得到我正在等待的结果。
Any one has another Idea
任何人都有另一个想法
Code:
代码:
#include "cv.h"
#include "highgui.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
int main(int argc,char** argv) {
IplImage * img =0;
uchar *data;
int i,j,k;
int height,width,widthStep,nChannels;
img=cvLoadImage(argv[1],3);
height =img->height;
width = img->width;
widthStep= img->widthStep;
nChannels = img->nChannels;
data=(uchar*)img->imageData;
IplImage* img1=cvCreateImage(cvSize(height/2,width/2),IPL_DEPTH_8U,nChannels);
for(i=0;i<height/2;i++){
for(j=0;j<width/2;j++){
for(k=0;k<3;k++){
img1->imageData[i*widthStep+j*nChannels]=data[i*widthStep+j*nChannels];
}
}
}
cvShowImage("image_Originale2",img1);
cvWaitKey(0);
cvReleaseImage(&img);
return 0;
}
采纳答案by karlphillip
What you are trying to accomplish can be done by setting a ROI(Region of Interest) on that image and copying that portion defined by the ROI to a new image.
您可以通过在该图像上设置ROI(感兴趣区域)并将该 ROI 定义的部分复制到新图像来完成您要完成的任务。
You can see a demo using IplImage
on this post.
您可以在这篇文章中看到使用的演示IplImage
。
These posts show uses of ROI to solve different scenarios:
这些帖子展示了使用 ROI 来解决不同的场景:
- MultiCrops in same image
- Setting ROI with mouse from a rectangle on a video
- Put Image in contour (OpenCV)
- IplImage inside IplImage
It's important to note that your code is using the C interfaceof OpenCV. The C++ interface offers cv::Mat
, which is the equivalent of IplImage
. In other words, what you are looking for is a C solutionto the problem.
请务必注意,您的代码使用的是 OpenCV的C 接口。C++ 接口提供cv::Mat
,相当于IplImage
. 换句话说,您正在寻找的是该问题的C 解决方案。
回答by Froyo
You should use cv::Mat
's copy constructor. It's much better than IplImage
:
您应该使用cv::Mat
的复制构造函数。它比IplImage
:
int x = 10,
y = 20,
width = 200,
height = 200;
Mat img1, img2;
img1 = imread("Lenna.png");
img2 = img1(Rect(x, y, width, height));
回答by Aerospace
Using copy constructor :
使用复制构造函数:
cv::Mat whole = ...; // from imread or anything else
cv::Mat part(
whole,
cv::Range( 20, 220 ), // rows
cv::Range( 10, 210 ));// cols
回答by Boyko Perfanov
Look up the cvSetImageROI()function.
查找cvSetImageROI()函数。
Sets an image Region Of Interest (ROI) for a given rectangle.
为给定的矩形设置图像感兴趣区域 (ROI)。