本文介绍了如何使用Python从原始图像中删除所有检测到的线条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试删除图像中存在的所有行。
我能够检测到线条,但当我试图删除线条时,我仍然在最终图像中得到几条小线条。我已经使用cv2.getStructuringElement
获得了水平线和垂直线。在某些情况下,最终图像完全失真,我无法前进
图片来自Google
res = verticle_lines_img + horizontal_lines_img
res = cv2.bitwise_not(res)
fin=cv2.bitwise_or(img_bin, res,mask =cv2.bitwise_not(res))
fin= cv2.bitwise_not(fin)
exp =255-res
final = cv2.bitwise_and(exp,img_bin)
final = cv2.bitwise_not(final)
exp = ~exp
finalised = cv2.bitwise_and(img_bin,final)
finalised = cv2.bitwise_not(finalised)
请帮帮我!谢谢
推荐答案
以下是一种方法
- 将图像转换为灰度
- 获取二值图像的大津阈值
- 删除水平线
- 删除垂直线
转换为灰度后,我们使用Otsu的阈值来获得二值图像
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
从这里我们构造了一个特殊的水平核来检测水平线。一旦检测到行,我们就填入行以有效地删除行
# Remove horizontal
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,1))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(image, [c], -1, (255,255,255), 2)
类似地,为了删除竖线,我们构造了一个特殊的垂直内核
# Remove vertical
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,10))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(image, [c], -1, (255,255,255), 2)
以下是检测到的绿色行
结果
您可以通过调整内核大小来微调结果。例如,将(10,1)
更改为(15,1)
将加强线条检测,而将其降低为(5,1)
将放松检测
完整代码
import cv2
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Remove horizontal
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,1))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(image, [c], -1, (255,255,255), 2)
# Remove vertical
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,10))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(image, [c], -1, (255,255,255), 2)
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()
这篇关于如何使用Python从原始图像中删除所有检测到的线条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!