記錄點滴
import numpy as np
from numpy import *
# boxes is a list of size (n x 5) (x1, y1, x2, y2, score)
# trial is a numpy array of size (n x 5)
def nms (boxes,overlap):
if not boxes:
pick = []
else:
trial = zeros((len(boxes),5),dtype=float64)
trial[:] = boxes[:]
x1 = trial[:,0]
y1 = trial[:,1]
x2 = trial[:,2]
y2 = trial[:,3]
score = trial[:,4]
area = (x2-x1+1)*(y2-y1+1)
#vals = sort(score)
I = argsort(score) # sort by score, from the smallest to biggest
pick = []
count = 1
while (I.size!=0):
#print "Iteration:",count
last = I.size
i = I[last-1]
pick.append(i)
suppress = [last-1]
for pos in range(last-1):
j = I[pos]
xx1 = max(x1[i],x1[j])
yy1 = max(y1[i],y1[j])
xx2 = min(x2[i],x2[j])
yy2 = min(y2[i],y2[j])
w = xx2-xx1+1
h = yy2-yy1+1
if (w>0 and h>0):
o = w*h/area[j]
print "Overlap is",o
if (o >overlap):
suppress.append(pos)
I = delete(I,suppress)
count = count + 1
return pick
from moviepy.editor import VideoFileClip
import cv2
import numpy as np
import os
def process_1(img):
mask = cv2.inRange(img, (36, 0, 0), (70, 255,255))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
mask = cv2.Canny(mask, 100, 300)
mask = cv2.GaussianBlur(mask, (1, 1), 0)
mask = cv2.Canny(mask, 100, 300)
im2, cnts, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
cv2.drawContours(img, cnts, -1, (0,255,0), 3)
return img
def process_2(img):
mask = cv2.inRange(img, (36, 0, 0), (70, 255,255))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
mask = cv2.Canny(mask, 100, 300)
mask = cv2.GaussianBlur(mask, (1, 1), 0)
mask = cv2.Canny(mask, 100, 300)
im2, cnts, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
rects = []
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
x, y, w, h = cv2.boundingRect(approx)
if h >= 15:
# if height is enough
# create rectangle for bounding
rect = (x, y, w, h)
rects.append(rect)
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 1)# get largest five contour area
## slice the green
imask = mask>0
green = np.zeros_like(img, np.uint8)
green[imask] = img[imask]
return img
cap = cv2.VideoCapture('./greenObject.mp4',0)
while(cap.isOpened()):
ret, frame = cap.read()
if ret is True:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
im_process = process_{optional}(hsv)
# x, y, w, h = cv2.findNonZero(im_process)
im_process = cv2.cvtColor(im_process, cv2.COLOR_HSV2BGR)
cv2.imshow('frame',im_process)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()