简体   繁体   English

使用 Python OpenCV 裁剪部分图像的简单方法是什么

[英]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.在上面的代码中,您可以看到我已经定义了一个 function 调用on_mouse ,它基本上为我们提供了鼠标在图像上单击的任何位置的坐标 (x, y)。 This helps in getting the x1, y1 and x2, y2 coordinates of the area we want to crop.这有助于获取我们要裁剪区域的x1, y1x2, y2坐标。 In below image, I am trying to crop the area of giraffe .在下图中,我试图裁剪giraffe的区域。 So I clicked on top left corner near giraffe which gave me the coordinates as X: 470 | Y: 179所以我点击了长颈鹿附近的左上角,坐标为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: 470 | Y: 179然后我点击了长颈鹿的右下角,它给了我坐标X: 645 | Y: 511 X: 645 | Y: 511 . X: 645 | Y: 511 When using them in above code, it gives below output在上面的代码中使用它们时,它给出以下 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?任何人都可以帮助我了解如何裁剪它以及这些x1, y1 and x2, y2表示什么? 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.这意味着前 2 对你需要定义行开始结束坐标,这意味着Y 轴坐标,然后是列开始结束坐标,这意味着X 轴坐标。 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. (x1, y1) 是起点的坐标,而 (x2, y2) 是图像中的终点。 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.在矩形中,您可以将它们视为左上角是 (x1, y1) 而 (x2, y2) 是右下角 - 或者就像宽度和高度一样。

But while cropping they have a little reverse format但是在裁剪时它们有一点反向格式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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