Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop an image in OpenCV using Python

Tags:

python

opencv

How can I crop images, like I've done before in PIL, using OpenCV.

Working example on PIL

im = Image.open('0.png').convert('L') im = im.crop((1, 1, 98, 33)) im.save('_0.png') 

But how I can do it on OpenCV?

This is what I tried:

im = cv.imread('0.png', cv.CV_LOAD_IMAGE_GRAYSCALE) (thresh, im_bw) = cv.threshold(im, 128, 255, cv.THRESH_OTSU) im = cv.getRectSubPix(im_bw, (98, 33), (1, 1)) cv.imshow('Img', im) cv.waitKey(0) 

But it doesn't work.

I think I incorrectly used getRectSubPix. If this is the case, please explain how I can correctly use this function.

like image 335
Nolik Avatar asked Mar 23 '13 17:03

Nolik


People also ask

How do I crop an image to a specific size in Python?

Use resize() to resize the whole image instead of cutting out a part of the image, and use putalpha() to create a transparent image by cutting out a shape other than a rectangle (such as a circle). Use slicing to crop the image represented by the NumPy array ndarray . Import Image from PIL and open the target image.

How do I crop a face in OpenCV?

cv2. rectangle() function used for draw rectangle over the detected object, img is input image, (x,y),(x+w, y+h) are locations of rectangle,(0,0,255) is color of a rectangle this argument gets passed as a tuple for BGR,we would use (0,0,255) for red, 2 is thickness of rectangle.

How do you crop an image in Python?

crop() method is used to crop a rectangular portion of any image. Parameters: box – a 4-tuple defining the left, upper, right, and lower pixel coordinate. Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple).

How do I crop a rectangle in OpenCV?

To crop an image to a certain area with OpenCV, use NumPy slicing img[y:y+height, x:x+width] with the (x, y) starting point on the upper left and (x+width, y+height) ending point on the lower right. Those two points unambiguously define the rectangle to be cropped.


2 Answers

It's very simple. Use numpy slicing.

import cv2 img = cv2.imread("lenna.png") crop_img = img[y:y+h, x:x+w] cv2.imshow("cropped", crop_img) cv2.waitKey(0) 
like image 81
Froyo Avatar answered Sep 19 '22 08:09

Froyo


i had this question and found another answer here: copy region of interest

If we consider (0,0) as top left corner of image called im with left-to-right as x direction and top-to-bottom as y direction. and we have (x1,y1) as the top-left vertex and (x2,y2) as the bottom-right vertex of a rectangle region within that image, then:

roi = im[y1:y2, x1:x2] 

here is a comprehensive resource on numpy array indexing and slicing which can tell you more about things like cropping a part of an image. images would be stored as a numpy array in opencv2.

:)

like image 27
samkhan13 Avatar answered Sep 17 '22 08:09

samkhan13