Use the Probabilistic Hough Line Transform:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
frame = cv2.imread("crop.jpg")
# It converts the BGR color space of image to HSV color space
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Threshold of blue in HSV space
lower_green = np.array([21, 115, 0])
upper_green = np.array([179, 255, 255])
# preparing the mask to overlay
mask = cv2.inRange(hsv, lower_green, upper_green)
mask = cv2.blur(mask, (5,5))
ret, mask = cv2.threshold(mask, 128, 255, cv2.THRESH_BINARY)
edges = cv2.Canny(mask,100,200)
# The black region in the mask has the value of 0,
# so when multiplied with original image removes all non-blue regions
result = cv2.bitwise_and(frame, frame, mask = mask)
cdst = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
linesP = cv2.HoughLinesP(edges, 1, np.pi / 180, 50, None, 100, 30)
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
cv2.line(cdst, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv2.LINE_AA)
cv2.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdst)
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.waitKey(-1)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…