簡體   English   中英

使用霍夫變換檢測深色線條和末端線條

[英]Detect lines with dark color and end lines using Hough Tranform

我試圖檢測垂直線,其中像素 RGB 的每種顏色都小於 100 |暗| ,這是一個示例 RGB (100,100,100)。

import numpy as np
import cv2

img = cv2.imread('testD2.png')

lower = np.array([0, 0, 0], dtype = "uint8")
upper = np.array([100,100,100], dtype = "uint8")
mask = cv2.inRange(img, lower, upper)
img = cv2.bitwise_and(img, img, mask = mask)

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength=img.shape[1]-300
lines = cv2.HoughLinesP(image=edges,rho=0.02,theta=np.pi/500, threshold=10,lines=np.array([]), minLineLength=minLineLength,maxLineGap=100)

if lines is not None:
    a,b,c = lines.shape
    for i in range(a):
        cv2.line(img, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA)



cv2.imshow('edges', edges)
cv2.imshow('result', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

我也必須改變結束線的顏色,我的意思是第一行和最后一行。

這是圖像

使用cv2.findContours()可能效果更好:

您可以使用cv2.findContours()cv2.boundingRect()來識別條形並返回描述這些矩形的信息 (x,y,h,w)。 這里有一些例子。

如果您只想識別線條並標記它們,您可以執行以下操作:

import cv2
import numpy as np

img = cv2.imread('oVKlP.png')
g = cv2.imread('oVKlP.png',0)
(T, mask) = cv2.threshold(g, 100, 255, cv2.THRESH_BINARY_INV)

_, contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img = cv2.drawContours(img.copy(), contours, -1, (0,255,0), 2)

cv2.imwrite('just_contours.png',img)

結果:

在此處輸入圖片說明

如果您想顯示一些行信息,例如可能是條形一側的x value ,您可以執行以下操作:

import cv2
import numpy as np

img = cv2.imread('oVKlP.png')
g = cv2.imread('oVKlP.png',0)
(T, mask) = cv2.threshold(g, 100, 255, cv2.THRESH_BINARY_INV)

_, contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# bounds with x,y,h,w for each bar
bounds = [cv2.boundingRect(i) for i in contours]
bounds.reverse()

img = cv2.drawContours(img.copy(), contours, -1, (0,0,255), 2)

font = cv2.FONT_HERSHEY_SIMPLEX

n = 20
b = 0

for (x,y,w,h) in bounds:
    cv2.circle(img, (x,y+n+10), 5, (0, 255, 0), -1, cv2.LINE_AA)
    cv2.putText(img, '{0}'.format(x), (x-b, y+n), font, .6, (255, 0, 255), 2, cv2.LINE_AA)
    n+=33
    b+=3

cv2.imwrite('fancy_marks.png',img)

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM