Home > Mobile >  What is the easy way to crop a part of image using Python OpenCV
What is the easy way to crop a part of image using Python OpenCV

Time:03-18

I have below code to crop a part of image:

import cv2

def on_mouse(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        print("X: {} | Y: {}".format(x, y))

win_name = "Image"
cv2.namedWindow(win_name)
cv2.setMouseCallback(win_name, on_mouse)

img = cv2.imread('park.jpg')
cropImg = img[179:470, 511:645]

cv2.imshow(win_name, img)
cv2.imshow("Crop", cropImg)
cv2.waitKey(0)
cv2.destroyAllWindows()

In the above code, you can see that I have defined a function call on_mouse which basically gives us the coordinates (x, y) wherever the mouse clicks on the image. This helps in getting the x1, y1 and x2, y2 coordinates of the area we want to crop. In below image, I am trying to crop the area of giraffe. So I clicked on top left corner near giraffe which gave me the coordinates as X: 470 | Y: 179 and then I clicked bottom right corner of the giraffe which gave me the coordinates of X: 645 | Y: 511. When using them in above code, it gives below output

enter image description here

Below is the original image

enter image description here

Can anyone please help me understand how can I crop it and what does these x1, y1 and x2, y2 denotes? Thanks

CodePudding user response:

The logic they designed that different than you think. It looks like:

cropImg = img[rowStart:rowEnd, colsStart:colsEnd]

It means first 2 couple you need to define row start and end coordinates which means Y axis coordinates and then column start and end coordinates which means X axis coordinates. So the line need to be changed in your code as:

cropImg = img[170:511,470:645]

Your result will change like :

enter image description here

CodePudding user response:

(x1, y1) are the coordinates of starting point, while (x2, y2) are the end points in the image. In a rectange you can think of them as top-left corner is (x1, y1) while (x2, y2) is bottom-right corner - or just like width and height.

But while cropping they have a little reverse format

cropImage = image[ y1: y2 , x1: x2] 
# or
cropImage = image[ Y: H, X: W ] 
  • Related