opencv-python:如何使用边界框坐标裁剪图像

opencv-python: how to crop image with bounding box coordinates

我在下图中用 绿色方框 标识的图像中识别出粉红色木材。现在我想根据框坐标裁剪图像。 我用图片描述我的意思。

边界框坐标: x, y, w, h = (50, 1034, 119, 72)

输入图像

预期输出(手动裁剪)

image1 - 从图像开始到粉色木头(边界框)开始的裁剪坐标

image2 - 从粉色木头(边界框)末端到图像末端的裁剪坐标

for image 1我写了blow代码但是写错了

x, y => 图像的开头 (0,0)

x, y => 粉色木头 (50 1034)

from PIL import Image
img = Image.open("img.png")
img2 = img.crop((0, 0, 50, 1034))
img2.save("1.png")

您可以select您感兴趣的区域作为数组:

import cv2

imagepath = yourPath
im = cv2.imread(imagepath)

imh, imw, _ = im.shape
x, y, w, h = (50, 1034, 119, 72)

img1 = im[:y, :]
img2 = im[y+h:imh, :]

cv2.imwrite('img1.tif', img1)
cv2.imwrite('img2.tif', img2)