简体   繁体   中英

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

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 X: 470 | Y: 179 and then I clicked bottom right corner of the giraffe which gave me the coordinates of X: 645 | Y: 511 X: 645 | Y: 511 . When using them in above code, it gives below output

在此处输入图像描述

Below is the original image

在此处输入图像描述

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

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:

在此处输入图像描述

(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 ] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM