python - 根据 cv2.HoughLines 的结果将图像拆分为多个图像
问题描述
我想根据黑线将此图像拆分为多个图像
我使用 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)
结果如下:
我想知道如何用这些绿线将图像分割成多个小图像
解决方案
假设image
是opencv读取图像作为nd数组的变量。
image = cv2.imread(image_filepath)
现在 iflines
是在 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
。
推荐阅读
- javascript - Mongoose 异常的事件名称
- google-apps-script - 如何保存来自用户的任何输入消息,这些消息通过谷歌表和对话流发送到我的在线聊天机器人
- swift - 如何从具有多个目标的项目中创建 xcframework
- github - C# GitHub API - 如何添加/删除拉取请求受让人?
- webpack - Webpack 5 字体解码失败和 OTS 解析错误的问题
- visual-studio - 在 VS2019 中创建的报表服务器项目上使用查询设计器中的“添加表”时出错
- amazon-dynamodb - 从另一列计算指数
- xml - Google Apps 脚本 XML 解释错误
- java - 使用 {spring boot & Thymeleaf} 对表中的外键元素进行排序
- docker - 从 docker 容器中移动配置卷,如何不再设置应用程序