本文共 8737 字,大约阅读时间需要 29 分钟。
import cv2import imutilsimport numpy as npfrom scipy.spatial import distance as distfrom imutils import perspectiveimport pycurlimport jsonimport mathimport timeimport pymysqlcap = cv2.VideoCapture(0, cv2.CAP_DSHOW)URL = "http://127.0.0.1:5000/name"def midpoint(ptA, ptB): return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)def post_data(dict): cor_num = pycurl.Curl() cor_num.setopt(pycurl.URL, URL) cor_num.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json']) # data = json.dumps({"name": "xgx", "sex": "male", "country": "china"}) data = json.dumps(dict) cor_num.setopt(pycurl.POST, 1) cor_num.setopt(pycurl.POSTFIELDS, data) cor_num.setopt(pycurl.VERBOSE, 1) cor_num.perform() cor_num.close()host = 'localhost'port = 3306db = 'cap_testing'user = 'root'password = '123456'def get_connection(): conn = pymysql.connect(host=host, port=port, db=db, user=user, password=password) return connppp = []iii = 1time_start = 0.0def detect_angle_demo(image): global iii global time_start global stable_time orig = image.copy() # cimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cimage = cv2.GaussianBlur(image, (9, 9), 2, 2) # RGB转HSV颜色空间 hsv = cv2.cvtColor(cimage, cv2.COLOR_BGR2HSV) gray = cv2.cvtColor(cimage, cv2.COLOR_BGR2GRAY) # 指定颜色的下限 lower_range = np.array([0, 43, 86]) # 指定颜色的上限 upper_range = np.array([10, 255, 255]) # 绿色区域 mask_g = cv2.inRange(hsv, (70, 43, 106), (80, 255, 255)) # 蓝色区域 mask_b = cv2.inRange(hsv, (110, 43, 126), (125, 255, 255)) mask_gb = { "green": mask_g, "blue": mask_b, } eee = cv2.inRange(hsv, (0, 0, 0), (180, 255, 255)) # # 指定颜色的下限 # lower_range = np.array([27, 86, 6]) # # 指定颜色的上限 # upper_range = np.array([80, 255, 255]) # 提取特定颜色的区域 mask = cv2.inRange(hsv, lower_range, upper_range) # mask = cv2.inRange(hsv, (36, 43, 46), (70, 255, 255)) mask2 = cv2.bitwise_not(mask) edged = cv2.dilate(mask, None, iterations=2) edged2 = cv2.erode(edged, None, iterations=2) cv2.imshow("mask", edged2) #cimage = cv2.GaussianBlur(cimage, (7, 7), 0) contours, hierarchy = cv2.findContours(edged2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 寻找最大轮廓 areas = [cv2.contourArea(c) for c in contours] # print(areas) if len(areas) >= 1: max_index = np.argmax(areas) cnt = contours[max_index] mianji = cv2.contourArea(cnt) print(mianji) # 得到最小方形区域,并得到方形区域的坐标 box = cv2.minAreaRect(cnt) box = cv2.boxPoints(box) box = np.array(box, dtype="int") box = perspective.order_points(box) (tl, tr, br, bl) = box # cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2) (centerX, centerY) = midpoint(tl, br) # cv2.circle(orig, (int(centerX), int(centerY)), 3, (255, 0, 0), -1) # cv2.circle(orig, (300, int(centerY)), 3, (0, 0, 255), -1) (x1, y1), radius = cv2.minEnclosingCircle(cnt) # 会返回一个二元组,第一个元素为圆心的坐标组成的元组,第二个元素为圆的半径值。 # cast to integers center = (int(x1), int(y1)) radius = int(radius) # draw the circle cv2.circle(orig, center, radius, (0, 255, 0), 2) # if (int(centerX) > 305): # passdata['index'] = 1 # elif (int(centerX) < 295): # passdata['index'] = 2 # else: # passdata['index'] = 0 # 计算图象上像素距离 # AB = dist.euclidean((centerX, centerY), (300, centerY)) # print("两点之间的像素距离是:", AB) if mianji > 5000: cv2.putText(orig, "The goal is existed", (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 0), 2) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.5, 30, param1=200, param2=120, minRadius=70, maxRadius=90) # 整数化,#把circles包含的圆心和半径的值变成整数 #circles = np.uint16(np.around(circles)) if circles is not None: for i in circles[0]: # 画出外边圆 cv2.circle(orig, (i[0], i[1]), i[2], (0, 255, 0), 2) # 画出圆心 cv2.circle(orig, (i[0], i[1]), 2, (0, 255, 0), 3) cv2.circle(orig, (300, i[1]), i[2], (0, 0, 255), 2) cv2.circle(orig, (300, i[1]), 2, (0, 0, 255), 3) x = int(i[0]) y = i[1] r = i[2] if (x > 301): # passdata['index'] = 1 # 顺时针 pass elif (x < 297): # passdata['index'] = 2 pass else: # passdata['index'] = 0 stable_time = stable_time + 1 passdata['datax'] = x print(r) pixels = (39.8 / 2) / r err = pixels * (abs(x - 300)) angle = math.asin(err/280) # print(3.14159*r*r) print(angle, err, pixels) if len(ppp) == 0: time_start = time.time() ppp.append(x) passdata['index'] = 5 ppp.append(x) time_end = time.time() sum_t = time_end - time_start passdata['time'] = sum_t if stable_time == 50: passdata['index'] = 6 passdata['stabletime'] = sum_t elif stable_time >= 51: passdata['index'] = 6 sql = "INSERT INTO pages3 (X, Y, R, T, NUM) VALUES ('{0}','{1}', {2},{3},{4})".format(x, y, r, sum_t, iii) try: with conn.cursor() as cursor: cursor.execute(sql) conn.commit() except Exception as e: conn.rollback() iii = iii + 1 # print(ppp[0], ppp[-1]) # cv2.putText(orig, "{:.1f}mm".format(dt_mean),(int(x + 20), int(y + 20)), cv2.FONT_HERSHEY_SIMPLEX,0.65, (255, 255, 255), 2) else: # passdata['index'] = 0 print("未检测到圆") else: cv2.putText(orig, "The goal is not existed", (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 0), 2) passdata['datax'] = 0 for key, value in mask_gb.items(): target = cv2.bitwise_and(eee, eee, mask=value) cntss = cv2.findContours(target, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] # cnts = cv2.findContours(value, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) areas_big = [cv2.contourArea(c) for c in cntss] if len(areas_big) >= 1: max_index_bg = np.argmax(areas_big) cnt_bg = cntss[max_index_bg] areasbg = cv2.contourArea(cnt_bg) if areasbg < 4000: continue else: print(key) if key == "green": # 发送逆时针转向信号 passdata['direction'] = 2 if key == "blue": # 发送顺时针转向信号 passdata['direction'] = 1 passdata['index'] = 4 post_data(passdata) cv2.imshow("circles", orig) cv2.imshow("blue", mask_b) cv2.imshow("green", mask_g) #cv2.imshow("yuanshi", image) else: passdata['index'] = 4 print("未检测到物体")if __name__ == "__main__": conn = get_connection() cursor = conn.cursor(pymysql.cursors.DictCursor) # cursor.execute("DROP TABLE IF EXISTS pages2") # cursor.execute("CREATE TABLE pages3(id INT AUTO_INCREMENT PRIMARY KEY,X FLOAT ,Y FLOAT ,R FLOAT ,T FLOAT ,NUM INT, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP)") stable_time = 0 passdata = { 'index': 6, 'direction': 1, 'time': 0} while True: ret, frame = cap.read() frame = cv2.flip(frame, -1) frame = imutils.resize(frame, width=600, height=600) detect_angle_demo(frame) # time_end = time.time() # sum_t = time_end - time_start # print("耗费时间", sum_t) # if sum_t >= 60: # print("一分钟内检测的次数", iii) # break # w, h = frame.shape # if stable_time >= 50: # pass # break if cv2.waitKey(1) & 0xFF == ord('q'): # passdata['datax'] = 300 passdata['index'] = 0 post_data(passdata) cursor.close() conn.close() cap.release() cv2.destroyAllWindows() break
转载地址:http://kpfef.baihongyu.com/