gpt4 book ai didi

python - 如何从图像中裁剪边界框

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:04 25 4
gpt4 key购买 nike

稍微解释一下这个问题。我有一个已经包含白色边界框的图像,如下所示: Input image

我需要裁剪被边界框包围的图像部分。

FindContours 在这里似乎不起作用,所以我尝试使用以下代码:

import cv2
import numpy as np

bounding_box_image = cv2.imread('PedestrianRectangles/1/grim.pgm')

edges = cv2.Canny(bounding_box_image, 50, 100) # apertureSize=3

cv2.imshow('edge', edges)
cv2.waitKey(0)

lines = cv2.HoughLinesP(edges, rho=0.5, theta=1 * np.pi / 180,
threshold=100, minLineLength=100, maxLineGap=50)

# print(len(lines))

for i in lines:
for x1, y1, x2, y2 in i:
# print(x1, y1, x2, y2)
cv2.line(bounding_box_image, (x1, y1), (x2, y2), (0, 255, 0), 2)

cv2.imwrite('houghlines5.jpg', bounding_box_image)

没有任何成功。摆弄参数也无济于事。我的代码片段的结果显示在下图中: Output

我有想法在线检测等之后进行裁剪

我是 opencv 的新手,因此不胜感激。我缺少解决此问题的好方法或简单方法吗?谷歌搜索无济于事,因此任何链接、代码片段都会有所帮助。

最佳答案

感谢 Silencer,在他的帮助下我能够让它工作,所以我会提供代码并希望它能帮助其他人:

import cv2
import numpy as np

bounding_box_image = cv2.imread('PedestrianRectangles/1/grim.pgm')
grayimage = cv2.cvtColor(bounding_box_image, cv2.COLOR_BGR2GRAY)

ret, mask = cv2.threshold(grayimage, 254, 255, cv2.THRESH_BINARY)

cv2.imshow('mask', mask)
cv2.waitKey(0)

image, contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)

for contour in contours:

if cv2.contourArea(contour) < 200:
continue

rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)

ext_left = tuple(contour[contour[:, :, 0].argmin()][0])
ext_right = tuple(contour[contour[:, :, 0].argmax()][0])
ext_top = tuple(contour[contour[:, :, 1].argmin()][0])
ext_bot = tuple(contour[contour[:, :, 1].argmax()][0])

roi_corners = np.array([box], dtype=np.int32)

cv2.polylines(bounding_box_image, roi_corners, 1, (255, 0, 0), 3)
cv2.imshow('image', bounding_box_image)
cv2.waitKey(0)

cropped_image = grayimage[ext_top[1]:ext_bot[1], ext_left[0]:ext_right[0]]
cv2.imwrite('crop.jpg', cropped_image)

然后输出output image

关于python - 如何从图像中裁剪边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50331025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com