[OpenCV] Image Crop

꾸준희
|2020. 4. 29. 00:15
728x90
반응형

 

OpenCV 에서 ROI 만큼 이미지를 Crop 시키는 방법은 아래와 같다. 

간단한 방법인데, 잊지않으려고 정리한다.

 

 

 

Python 구현 

# x, y, w, h refers to the ROI for which the image is to be cropped.
img = cv2.imread('test.jpg')
cropped_img = img[y: y + h, x: x + w]

 

C++ 구현

Mat img = cv::imread("test.jpg");
Rect bounds(0,0,img.cols,img.rows);
Rect r(x,y,width,height); // partly outside
Mat roi = img( r & bounds ); // cropped to fit image

 

위와 같이 구현하면 아래와 같은 에러를 방지함

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in cv::Mat::Mat

 

 

 

참고자료 : https://answers.opencv.org/question/179280/cropping-of-images-in-c-vs-python/

 

Cropping of images in c++ vs python - OpenCV Q&A Forum

Cropping of images in c++ vs python edit I got a strange error that I couldn't figure out where i went wrong.. I am trying to port from Python over to C++ the following cropping code: In Python: # x, y, w, h refers to the ROI for which the image is to be c

answers.opencv.org

 

728x90
반응형