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.
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.
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.
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).
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.
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)
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.
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With