我们从Python开源项目中,提取了以下3个代码示例,用于说明如何使用cv2.meanShift()。
def deal(self,frame): frame=frame.copy() track_window=self.track_window term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 ) roi_hist=self.roi_hist dst = cv2.calcBackProject([frame],[0],roi_hist,[0,180],1) if self.m=='m': ret, track_window_r = cv2.meanShift(dst, track_window, term_crit) x,y,w,h = track_window_r img2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2) elif self.m=='c': ret, track_window_r = cv2.CamShift(dst, track_window, term_crit) pts = cv2.boxPoints(ret) pts = np.int0(pts) img2 = cv2.polylines(frame,[pts],True, 255,2) rectsNew=[] center1=(track_window[0]+track_window[2]//2,track_window[1]+track_window[3]//2) center2=(track_window_r[0]+track_window_r[2]//2,track_window_r[1]+track_window_r[3]//2) img2 = cv2.line(img2,center1,center2,color=0) rectsNew=track_window_r # x,y,w,h = track_window # img2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2) cv2.imshow('img2',img2) cv2.waitKey(0) cv2.destroyAllWindows() return rectsNew
def test_features(): from atx.drivers.android_minicap import AndroidDeviceMinicap cv2.namedWindow("preview") d = AndroidDeviceMinicap() # r, h, c, w = 200, 100, 200, 100 # track_window = (c, r, w, h) # oldimg = cv2.imread('base1.png') # roi = oldimg[r:r+h, c:c+w] # hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) # mask = cv2.inRange(hsv_roi, 0, 255) # roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0,180]) # cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX) # term_cirt = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1) while True: try: w, h = d._screen.shape[:2] img = cv2.resize(d._screen, (h/2, w/2)) cv2.imshow('preview', img) hist = cv2.calcHist([img], [0], None, [256], [0,256]) plt.plot(plt.hist(hist.ravel(), 256)) plt.show() # if img.shape == oldimg.shape: # # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # # ret, track_window = cv2.meanShift(hsv, track_window, term_cirt) # # x, y, w, h = track_window # cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2) # cv2.imshow('preview', img) # # cv2.imshow('preview', img) cv2.waitKey(1) except KeyboardInterrupt: break cv2.destroyWindow('preview')