稍微解释一下这个问题。我有一个图像已经包含一个白色边框,如下所示: 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比较新,所以请帮助我们。我缺少这个问题的好方法吗?谷歌搜索没有帮助所以任何链接,代码片段将有所帮助。
答案 0 :(得分:1)
答案 1 :(得分:1)
感谢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)