Facebook
From Wet Armadillo, 6 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 267
  1. import cv2
  2. import numpy as np
  3. import math
  4.  
  5. cap = cv2.VideoCapture(0)
  6.  
  7. while(cap.isOpened()):
  8.     ret, img = cap.read()
  9.     cv2.rectangle(img,(300,300),(100,100),(0,255,0),0)
  10.     crop_img = img[100:300, 100:300]
  11.     grey = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
  12.     value = (37,37)
  13.     blurred = cv2.GaussianBlur(grey, value, 0)
  14.     _, thresh1 = cv2.threshold(blurred, 127, 255,
  15.                                cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
  16.     #cv2.imshow('Thresholded', thresh1)
  17.     #print cv2.findContours(thresh1.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
  18.     _, contours, hierarchy = cv2.findContours(thresh1.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
  19.  
  20.     max_area = -1
  21.     print len(contours)
  22.     for i in range(len(contours)):
  23.         cnt=contours[i]
  24.         area = cv2.contourArea(cnt)
  25.         if(area>max_area):
  26.             max_area=area
  27.             ci=i
  28.     cnt=contours[ci]
  29.     x,y,w,h = cv2.boundingRect(cnt)
  30.     cv2.rectangle(crop_img,(x,y),(x+w,y+h),(0,0,255),0)
  31.     hull = cv2.convexHull(cnt)
  32.     drawing = np.zeros(crop_img.shape,np.uint8)
  33.     cv2.drawContours(drawing,[cnt],0,(0,255,0),0)
  34.     cv2.drawContours(drawing,[hull],0,(0,0,255),0)
  35.     hull = cv2.convexHull(cnt,returnPoints = False)
  36.     defects = cv2.convexityDefects(cnt,hull)
  37.     count_defects = 0
  38.     cv2.drawContours(thresh1, contours, -1, (0,255,0), 3)
  39.     for i in range(defects.shape[0]):
  40.         s,e,f,d = defects[i,0]
  41.         start = tuple(cnt[s][0])
  42.         end = tuple(cnt[e][0])
  43.         far = tuple(cnt[f][0])
  44.         a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2)
  45.         b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2)
  46.         c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2)
  47.         angle = math.acos((b**2 + c**2 - a**2)/(2*b*c)) * 57
  48.         if angle <= 90:
  49.             count_defects += 1
  50.             cv2.circle(crop_img,far,1,[0,0,255],-1)
  51.         dist = cv2.pointPolygonTest(cnt,far,True)
  52.         cv2.line(crop_img,start,end,[0,255,0],2)
  53.         cv2.circle(crop_img,far,5,[0,0,255],-1)
  54.  
  55.     if count_defects>3:
  56.         cv2.putText(img,"ABIERTA", (50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 4)
  57.     else:
  58.         cv2.putText(img,"CERRADA", (50,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 4)
  59.  
  60.     cv2.imshow('drawing', drawing)
  61.     cv2.imshow('end', crop_img)
  62.     cv2.imshow('Gesture', img)
  63.  
  64.     all_img = np.hstack((drawing, crop_img))
  65.     cv2.imshow('Contours', all_img)
  66.     k = cv2.waitKey(10)
  67.     if k == 27:
  68.         cap.release()
  69.         break