思路:
1、摄像头和激光笔要产生夹角,人为让激光线产生落差
2、降低摄像头亮度,不然会在提取激光线的产生各种光斑干扰
3、BGR转HSV提取红色区域,如果效果不好再加OTSU二值分割
4、霍夫直线检测
5、检测直线对掩码图做差
6、形态学操作处理噪点
import os
from PIL import Image
import cv2
import numpy as np
import math
index = 0
def morphology(img):
ret,thresh2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
op_close = cv2.morphologyEx(thresh2, cv2.MORPH_CLOSE, kernel)
op_open = cv2.morphologyEx(op_close, cv2.MORPH_OPEN, kernel)
return op_open
def mask(img_mask,raw):
img_mask_1,img_mask_2,img_mask_3 = cv2.split(img_mask)
x = np.zeros(img_mask_2.shape).astype('uint8')
img_mask_x = cv2.merge([x,img_mask_1,x])
masked = cv2.add(raw, img_mask_x)
return masked
def extract_red(img):
img_hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
rows, cols, channels = img.shape
lower_red = np.array([0, 43, 46])
upper_red = np.array([10, 255, 255])
mask0 = cv2.inRange(img_hsv,lower_red,upper_red)
lower_red = np.array([156, 43, 46])
upper_red = np.array([180, 255, 255])
mask1 = cv2.inRange(img_hsv,lower_red,upper_red)
maskpp = mask0 + mask1
return maskpp
def operation(img):
img = cv2.resize(img, (1152,648))
raw = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
raw_gray = cv2.cvtColor(raw,cv2.COLOR_RGB2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5, 5))
eroded = cv2.erode(raw_gray,kernel)
lines = cv2.HoughLinesP(eroded,1,np.pi/180,60,minLineLength=100,maxLineGap=20)
if lines is not None:
line = lines[:,0,:]
sums = np.zeros(raw_gray.shape).astype('uint8')
for x1,y1,x2,y2 in line[:]:
mask_line = np.zeros(raw_gray.shape).astype('uint8')
cv2.line(mask_line,(x1,y1),(x2,y2),(255,255,255),1)
b,g,r = cv2.split(raw)
img2subtraction = cv2.subtract(mask_line,b)
sums = sums + img2subtraction
sums[ sums > 255 ] = 255
return sums
else:
sums = np.zeros(raw_gray.shape).astype('uint8')
return sums
def get_length(x1,y1,x2,y2):
point1=np.array([x1,y1])
point2=np.array([x2,y2])
x=point2-point1
res=math.hypot(x[0],x[1])
return res
def get_gradient(x1,y1,x2,y2):
if x1 != x2 :
k = (y2-y1) / (x2-x1)
return k
else:
k = 0
return k
def start(img):
masks = extract_red(img)
sums = operation(masks)
return sums
cap = cv2.VideoCapture("0.mp4")
while(1):
ret, frame = cap.read()