我想根据黑线将此图像分成多张图像
我使用cv2.HoughLines获取一些行,合并它们以避免行重叠。 这是我的绘图代码:
# After get lines from cv2.HoughLines()
for line in lines:
rho, theta = line
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * (a))
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * (a))
cv2.line(image, (x1, y1), (x2, y2), (0, 200, 0), 2)
cv2.imwrite('results/result.jpg', image)
结果如下:
我想知道如何将这些图像分成带有绿线的多个小图像
答案 0 :(得分:1)
假设image
是变量,opencv将其作为nd数组读取图像。
image = cv2.imread(image_filepath)
现在,如果lines
是在像houghline转换之后分配的变量:
lines = cv2.HoughLinesP(...)
获取形状:
a,b,c = lines.shape
启动一个变量以获取坐标并附加边界框:
line_coords_list = []
for i in range(a):
line_coords_list.append([(lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3])])
现在,循环浏览边界框列表,裁剪主图像,并使用一些文件名将其写入:
temp_img = image[start_y_coordinate : end_y_coordinate , start_x_coorinate : end_x_coordinate]
temp_name = image_filepath[:-4] + "_"+str(start_y_coordinate )+"_"+str(end_y_coordinate)+ "_" + str(start_x_coorinate) + "_" + str(end_x_coordinate) + ".png"
cv2.imwrite(temp_name, temp_img)
如果您使用的是cv2.HoughLines(...)
,则可能必须使用以下命令在图像中找到轮廓:
_, blackAndWhite = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY_INV)
_,contours,h = cv2.findContours(blackAndWhite,cv2.RETR_LIST ,cv2.CHAIN_APPROX_SIMPLE)
,然后遍历轮廓:
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
line_coords_list.append((x,y,w,h))
在这里找到轮廓时,第三和第四项分别是宽度和高度。所以end_y_coordinate = y+h
和end_x_coordinate = x+w
。
答案 1 :(得分:0)
请参见“感兴趣的区域”
(Region of Interest opencv python-StackOverflow)
阅读以获取x / y:
({Hough Line Transform-Opencv Phyton教程1文档)