Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- import math
- cap = cv2.VideoCapture(0)
- vertices = None
- area = None
- def calc_box_vector(box):
- v_side = math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
- h_side = math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
- idx = [0, 1, 2, 3]
- if v_side < h_side:
- idx = [0, 3, 1, 2]
- return ((box[idx[0]][0] + box[idx[1]][0]) / 2, (box[idx[0]][1] + box[idx[1]][1]) / 2), (
- (box[idx[2]][0] + box[idx[3]][0]) / 2, (box[idx[2]][1] + box[idx[3]][1]) / 2)
- def get_vert_angle(p1, p2, w, h):
- px1 = p1[0] - w / 2
- px2 = p2[0] - w / 2
- py1 = h - p1[1]
- py2 = h - p2[1]
- angle = 90
- if px1 != px2:
- a = float(py2 - py1) / (px2 - px1) if px2 != px1 else 0
- b = py1 - a * px1
- angle = 0
- if a != 0:
- x0 = -b / a
- y1 = 1.0
- x1 = (y1 - b) / a
- dx = x1 - x0
- tg = y1 * y1 / dx / dx
- angle = 180 * np.arctan(tg) / np.pi
- if a < 0:
- angle = 180 - angle
- return angle
- T = 140
- def order_box(box):
- srt = np.argsort(box[:, 1])
- btm1 = box[srt[0]]
- btm2 = box[srt[1]]
- top1 = box[srt[2]]
- top2 = box[srt[3]]
- bc = btm1[0] < btm2[0]
- btm_l = btm1 if bc else btm2
- btm_r = btm2 if bc else btm1
- tc = top1[0] < top2[0]
- top_l = top1 if tc else top2
- top_r = top2 if tc else top1
- return np.array([top_l, top_r, btm_r, btm_l])
- def find_main_countour(image):
- im2, cnts, hierarchy = cv2.findContours(image, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
- C = None
- if cnts is not None and len(cnts) > 0:
- C = max(cnts, key=cv2.contourArea)
- if C is None:
- return None, None
- rect = cv2.minAreaRect(C)
- box = cv2.boxPoints(rect)
- box = np.int0(box)
- box = order_box(box)
- return C, box
- while 1:
- s, image = cap.read()
- h, w = image.shape[:2]
- hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
- blurred = cv2.GaussianBlur(hsv, (9, 9), 0)
- cropped = cv2.inRange(blurred,(0, 0, 0),(188, 255, 32))
- if cropped is None:
- continue
- cont, box = find_main_countour(cropped)
- if cont is None:
- continue
- p1, p2 = calc_box_vector(box)
- angle = get_vert_angle(p1, p2, w, h)
- shift = 100 * (p1[0] - w / 2) / (w / 2)
- cv2.drawContours(image, [cont], -1, (0, 0, 255), 3)
- cv2.drawContours(image, [box], 0, (255, 0, 0), 2)
- cv2.line(image, (int(p1[0]), int(p1[1])), (int(p2[0]), int(p2[1])), (0, 255, 0), 3)
- msg_a = "Angle {0}".format(int(angle))
- msg_s = "Shift {0}".format(int(shift))
- cv2.putText(image, msg_a, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
- cv2.putText(image, msg_s, (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
- cv2.imshow("Image", image)
- ch = cv2.waitKey(5) # ожидание кнопки для закрытия P.S. не помню какая кнопка, но ESC работает
- if ch == 27:
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement