1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| from types import NoneType import cv2 import numpy as np def slop(line): x1,y1,x2,y2 = line[0] return (y2-y1)/(x2-x1) def outlier(lines, threshold): slops = [slop(line) for line in lines] while len(lines) > 0: mean = np.mean(slops) diff = [abs(s - mean) for s in slops] idx = np.argmax(diff) if diff[idx] > threshold: slops.pop(idx) lines.pop(idx) else: break return lines def fit(lines): x = np.ravel([[line[0][0],line[0][2]] for line in lines]) y = np.ravel([[line[0][1],line[0][3]] for line in lines]) poly = np.polyfit(x, y, deg=1) point_min = (np.min(x),np.polyval(poly, np.min(x))) point_max = (np.max(x),np.polyval(poly, np.max(x))) return np.array([point_min, point_max], dtype=np.int32) cat = cv2.VideoCapture(0) cv2.namedWindow('img',cv2.WINDOW_NORMAL) cv2.resizeWindow('img',640,480) while True: ret, frame = cat.read() if not ret: break gray = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY) imgs = cv2.Canny(gray, 100, 200) lines = cv2.HoughLinesP(imgs, 1, np.pi/180,15,minLineLength=40,maxLineGap=20) if lines is None: continue Lines = [line for line in lines] lines = outlier(Lines, 0.2) Line = fit(lines) cv2.line(frame, tuple(Line[1]), tuple(Line[0]), color=(0, 255, 255), thickness=5) cv2.imshow('img',frame) if cv2.waitKey(10) == ord('q'): break cv2.destroyAllWindows()
|