def processImage(self, curframe): cv.Smooth(curframe, curframe) #Remove false positives if not self.absdiff_frame: #For the first time put values in difference, temp and moving_average self.absdiff_frame = cv.CloneImage(curframe) self.previous_frame = cv.CloneImage(curframe) cv.Convert( curframe, self.average_frame ) #Should convert because after runningavg take 32F pictures else: cv.RunningAvg(curframe, self.average_frame, 0.05) #Compute the average cv.Convert(self.average_frame, self.previous_frame) #Convert back to 8U frame cv.AbsDiff(curframe, self.previous_frame, self.absdiff_frame) # moving_average - curframe cv.CvtColor( self.absdiff_frame, self.gray_frame, cv.CV_RGB2GRAY) #Convert to gray otherwise can't do threshold cv.Threshold(self.gray_frame, self.gray_frame, 50, 255, cv.CV_THRESH_BINARY) cv.Dilate(self.gray_frame, self.gray_frame, None, 15) #to get object blobs cv.Erode(self.gray_frame, self.gray_frame, None, 10)
def getIris(frame): iris = [] copyImg = cv.CloneImage(frame) resImg = cv.CloneImage(frame) grayImg = cv.CreateImage(cv.GetSize(frame), 8, 1) mask = cv.CreateImage(cv.GetSize(frame), 8, 1) storage = cv.CreateMat(frame.width, 1, cv.CV_32FC3) cv.CvtColor(frame,grayImg,cv.CV_BGR2GRAY) cv.Canny(grayImg, grayImg, 5, 70, 3) cv.Smooth(grayImg,grayImg,cv.CV_GAUSSIAN, 7, 7) circles = getCircles(grayImg) iris.append(resImg) for circle in circles: rad = int(circle[0][2]) global radius radius = rad cv.Circle(mask, centroid, rad, cv.CV_RGB(255,255,255), cv.CV_FILLED) cv.Not(mask,mask) cv.Sub(frame,copyImg,resImg,mask) x = int(centroid[0] - rad) y = int(centroid[1] - rad) w = int(rad * 2) h = w cv.SetImageROI(resImg, (x,y,w,h)) cropImg = cv.CreateImage((w,h), 8, 3) cv.Copy(resImg,cropImg) cv.ResetImageROI(resImg) return(cropImg) return (resImg)
def template_match(img, refimg, confidence=0.6, xwin=19, ywin=19): """ Return all matches of refimg inside img, using Template Matching. (Gratefully) borrowed from: http://stackoverflow.com/questions/7670112/finding-a-subimage-inside-a-numpy-image/9253805# 9253805 Input: obj img: A numpy array representing an image obj refimg: A numpy array representing the reference image float confidence: threshold value (from [0,1]) for template matching Output: A tuple of (x,y) coodinates, w.r.t the coordinate system of img. """ # OpenCV requires either uint8, or float, but with floats it got # buggy and failed badly (I think it had to do with it not # correctly handling when 'img' had no decimals, but 'refimg' # had decimal expansions, which I suppose means that internally # OpenCV.matchTemplate does exact integer comparisons. img = img.astype('uint8') refimg = refimg.astype('uint8') I = cv.fromarray(img) ref = cv.fromarray(refimg) # I = cv.fromarray(np.copy(img)) # ref = cv.fromarray(np.copy(refimg)) I_s = cv.CreateMat(I.rows, I.cols, I.type) cv.Smooth(I, I_s, cv.CV_GAUSSIAN, param1=xwin, param2=ywin) ref_s = cv.CreateMat(ref.rows, ref.cols, ref.type) cv.Smooth(ref, ref_s, cv.CV_GAUSSIAN, param1=xwin, param2=ywin) # img = np.array(img, dtype='uint8') # refimg = np.array(refimg, dtype='uint8') result = cv.CreateMat(I_s.rows - ref_s.rows + 1, I_s.cols - ref_s.cols + 1, cv.CV_32F) cv.MatchTemplate(I_s, ref_s, result, cv.CV_TM_CCOEFF_NORMED) # result = cv2.matchTemplate(img, refimg, cv2.TM_CCOEFF_NORMED) # result is a 'similarity' matrix, with values from -1.0 (?) to 1.0, # where 1.0 is most similar to the template image. result_np = np.asarray(result) match_flatidxs = np.arange(result_np.size)[ (result_np > confidence).flatten()] return [flatidx_to_pixelidx(flatidx, result_np.shape) for flatidx in match_flatidxs]
def processImage(self, frame): cv.CvtColor(frame, self.frame2gray, cv.CV_RGB2GRAY) #Absdiff to get the difference between to the frames cv.AbsDiff(self.frame1gray, self.frame2gray, self.res) #Remove the noise and do the threshold cv.Smooth(self.res, self.res, cv.CV_BLUR, 5, 5) cv.MorphologyEx(self.res, self.res, None, None, cv.CV_MOP_OPEN) cv.MorphologyEx(self.res, self.res, None, None, cv.CV_MOP_CLOSE) cv.Threshold(self.res, self.res, 10, 255, cv.CV_THRESH_BINARY_INV)
def run(self): while True: img = cv.QueryFrame(self.capture) #blur the source image to reduce color noise cv.Smooth(img, img, cv.CV_BLUR, 3) #convert the image to hsv(Hue, Saturation, Value) so its #easier to determine the color to track(hue) hsv_img = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV) #limit all pixels that don't match our criteria, in this case we are #looking for purple but if you want you can adjust the first value in #both turples which is the hue range(120,140). OpenCV uses 0-180 as #a hue range for the HSV color model thresholded_img = cv.CreateImage(cv.GetSize(hsv_img), 8, 1) cv.InRangeS(hsv_img, (120, 80, 80), (140, 255, 255), thresholded_img) #determine the objects moments and check that the area is large #enough to be our object moments = cv.Moments(thresholded_img, 0) area = cv.GetCentralMoment(moments, 0, 0) #there can be noise in the video so ignore objects with small areas if (area > 100000): #determine the x and y coordinates of the center of the object #we are tracking by dividing the 1, 0 and 0, 1 moments by the area x = cv.GetSpatialMoment(moments, 1, 0) / area y = cv.GetSpatialMoment(moments, 0, 1) / area #print 'x: ' + str(x) + ' y: ' + str(y) + ' area: ' + str(area) #create an overlay to mark the center of the tracked object overlay = cv.CreateImage(cv.GetSize(img), 8, 3) cv.Circle(overlay, (x, y), 2, (255, 255, 255), 20) cv.Add(img, overlay, img) #add the thresholded image back to the img so we can see what was #left after it was applied cv.Merge(thresholded_img, None, None, None, img) #display the image cv.ShowImage(color_tracker_window, img) if cv.WaitKey(10) == 27: break
def applyEffect(self, image, width, height): ipl_img = cv2.cv.CreateImageHeader((image.shape[1], image.shape[0]), cv.IPL_DEPTH_8U, 3) cv2.cv.SetData(ipl_img, image.tostring(), image.dtype.itemsize * 3 * image.shape[1]) gray = cv.CreateImage((width, height), 8, 1) # tuple as the first arg dst_img = cv.CreateImage(cv.GetSize(ipl_img), cv.IPL_DEPTH_8U, 3) # _16S => cv2.cv.iplimage if self.effect == 'dilate': cv.Dilate(ipl_img, dst_img, None, 5) elif self.effect == 'laplace': cv.Laplace(ipl_img, dst_img, 3) elif self.effect == 'smooth': cv.Smooth(ipl_img, dst_img, cv.CV_GAUSSIAN) elif self.effect == 'erode': cv.Erode(ipl_img, dst_img, None, 1) cv.Convert(dst_img, ipl_img) return self.ipl2tk_image(dst_img)
import cv2 import numpy as np import cv2 cap = cv2.VideoCapture(0) cv2.namedWindow("original") try: while(True): ret, img = cap.read() if (not ret): break blurry = cv2.Smooth(img, img, cv.CV_BLUR, 3) cv2.imshow('original', blurry) if cv2.waitKey(33) == 27: break cap.release() cv2.destroyAllWindows() except: pass
def run(self): # Capture first frame to get size frame = cv.QueryFrame(self.capture) frame_size = cv.GetSize(frame) width = frame.width height = frame.height surface = width * height #Surface area of the image cursurface = 0 #Hold the current surface that have changed grey_image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) moving_average = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_32F, 3) difference = None while True: color_image = cv.QueryFrame(self.capture) cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0) #Remove false positives if not difference: #For the first time put values in difference, temp and moving_average difference = cv.CloneImage(color_image) temp = cv.CloneImage(color_image) cv.ConvertScale(color_image, moving_average, 1.0, 0.0) else: cv.RunningAvg(color_image, moving_average, 0.020, None) #Compute the average # Convert the scale of the moving average. cv.ConvertScale(moving_average, temp, 1.0, 0.0) # Minus the current frame from the moving average. cv.AbsDiff(color_image, temp, difference) #Convert the image so that it can be thresholded cv.CvtColor(difference, grey_image, cv.CV_RGB2GRAY) cv.Threshold(grey_image, grey_image, 70, 255, cv.CV_THRESH_BINARY) cv.Dilate(grey_image, grey_image, None, 18) #to get object blobs cv.Erode(grey_image, grey_image, None, 10) # Find contours storage = cv.CreateMemStorage(0) contours = cv.FindContours(grey_image, storage, cv.CV_RETR_EXTERNAL, cv.CV_CHAIN_APPROX_SIMPLE) backcontours = contours #Save contours while contours: #For all contours compute the area cursurface += cv.ContourArea(contours) contours = contours.h_next() avg = ( cursurface * 100 ) / surface #Calculate the average of contour area on the total size if avg > self.ceil: print("Something is moving !") #print avg,"%" cursurface = 0 #Put back the current surface to 0 #Draw the contours on the image _red = (0, 0, 255) #Red for external contours _green = (0, 255, 0) # Gren internal contours levels = 1 #1 contours drawn, 2 internal contours as well, 3 ... cv.DrawContours(color_image, backcontours, _red, _green, levels, 2, cv.CV_FILLED) cv.ShowImage("Target", color_image) # Listen for ESC or ENTER key c = cv.WaitKey(7) % 0x100 if c == 27 or c == 10: break
# coding:UTF-8 import cv2 as cv from src import App image = cv.imread('D:/image/test.png', 0) cv.imshow("Original", image) grey = cv.CreateImage((image.width, image.height), 8, 1) # 8depth, 1 channel so grayscale cv.CvtColor(image, grey, cv.CV_RGBA2GRAY) # Convert to gray so act as a filter cv.imshow('Greyed', grey) # 平滑变换 smoothed = cv.CloneImage(image) cv.Smooth(image, smoothed, cv.CV_MEDIAN ) # Apply a smooth alogrithm with the specified algorithm cv.MEDIAN
def smoothImage(im, nbiter=0, filter=cv.CV_GAUSSIAN): for i in range(nbiter): cv.Smooth(im, im, filter)