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 __init__(self, img0): self.thresh1 = 255 self.thresh2 = 30 self.level =4 self.storage = cv.CreateMemStorage() cv.NamedWindow("Source", 0) cv.ShowImage("Source", img0) cv.NamedWindow("Segmentation", 0) cv.CreateTrackbar("Thresh1", "Segmentation", self.thresh1, 255, self.set_thresh1) cv.CreateTrackbar("Thresh2", "Segmentation", self.thresh2, 255, self.set_thresh2) self.image0 = cv.CloneImage(img0) self.image1 = cv.CloneImage(img0) cv.ShowImage("Segmentation", self.image1)
def redraw(): global draging global has_roi global roi_x0 global roi_y0 global cur_mouse_x global cur_mouse_y #Redraw ROI selection image2 = cv.CloneImage(current_image) # redraw old rect pen_width = 4 if rect_table.has_key(current_img_file_name): rects_in_table = rect_table[current_img_file_name] for r in rects_in_table: cv.Rectangle(image2, (r[0], r[1]), (r[0] + r[2], r[1] + r[3]), cv.CV_RGB(0, 255, 0), pen_width) # redraw new rect if has_roi: cv.Rectangle(image2, (roi_x0, roi_y0), (cur_mouse_x, cur_mouse_y), cv.CV_RGB(255, 0, 255), pen_width) # draw background if current_img_file_name in background_files: cv.Line(image2, (0, 0), (image2.width, image2.height), cv.CV_RGB(255, 0, 0)) cv.Line(image2, (0, image2.height), (image2.width, 0), cv.CV_RGB(255, 0, 0)) cv.ShowImage(window_name, image2)
def getContours(im, approx_value=1): #Return contours approximated storage = cv.CreateMemStorage(0) contours = cv.FindContours(cv.CloneImage(im), storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) contourLow = cv.ApproxPoly(contours, storage, cv.CV_POLY_APPROX_DP, approx_value, approx_value) return contourLow
def getPupil(frame): pupilImg = cv.CreateImage(cv.GetSize(frame), 8, 1) cv.InRangeS(frame, (30,30,30), (80,80,80), pupilImg) contours = cv.FindContours(pupilImg, cv.CreateMemStorage(0), mode = cv.CV_RETR_EXTERNAL) del pupilImg pupilImg = cv.CloneImage(frame) while contours: moments = cv.Moments(contours) area = cv.GetCentralMoment(moments,0,0) if (area > 50): pupilArea = area x = cv.GetSpatialMoment(moments,1,0)/area y = cv.GetSpatialMoment(moments,0,1)/area pupil = contours global centroid centroid = (int(x),int(y)) cv.DrawContours(pupilImg, pupil, (0,0,0), (0,0,0), 2, cv.CV_FILLED) break contours = contours.h_next() return (pupilImg)
c = (float(imgSize[0]/2.0), float(imgSize[1]/2.0)) imgRes = cv.CreateImage((rad*3, int(360)), 8, 3) #cv.LogPolar(image,imgRes,c,50.0, cv.CV_INTER_LINEAR+cv.CV_WARP_FILL_OUTLIERS) cv.LogPolar(image,imgRes,c,60.0, cv.CV_INTER_LINEAR+cv.CV_WARP_FILL_OUTLIERS) return (imgRes) # Window creation for showing input, output cv.NamedWindow("input", cv.CV_WINDOW_AUTOSIZE) cv.NamedWindow("output", cv.CV_WINDOW_AUTOSIZE) cv.NamedWindow("normalized", cv.CV_WINDOW_AUTOSIZE) eyesList = os.listdir('images/eyes') key = 0 while True: eye = getNewEye(eyesList) frame = cv.LoadImage("images/eyes/"+eye) iris = cv.CloneImage(frame) output = getPupil(frame) iris = getIris(output) cv.ShowImage("input", frame) cv.ShowImage("output", iris) normImg = cv.CloneImage(iris) normImg = getPolar2CartImg(iris,radius) cv.ShowImage("normalized", normImg) key = cv.WaitKey(3000) # seems like Esc with NumLck equals 1048603 if (key == 27 or key == 1048603): break cv.DestroyAllWindows()
orig = cv.imread('lena.png') #im = cv.CreateImage(cv.GetSize(orig), 8, 1) im = cv.cvtColor(orig,cv.COLOR_BGR2GRAY) #cv.CvtColor(orig, im, cv.CV_BGR2GRAY) #Keep the original in colour to draw contours in the end cv.Threshold(im, im, 128, 255, cv.CV_THRESH_BINARY) cv.ShowImage("Threshold 1", im) element = cv.CreateStructuringElementEx(5*2+1, 5*2+1, 5, 5, cv.CV_SHAPE_RECT) cv.MorphologyEx(im, im, None, element, cv.CV_MOP_OPEN) #Open and close to make appear contours cv.MorphologyEx(im, im, None, element, cv.CV_MOP_CLOSE) cv.Threshold(im, im, 128, 255, cv.CV_THRESH_BINARY_INV) cv.ShowImage("After MorphologyEx", im) # -------------------------------- vals = cv.CloneImage(im) #Make a clone because FindContours can modify the image contours=cv.FindContours(vals, cv.CreateMemStorage(0), cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_SIMPLE, (0,0)) _red = (0, 0, 255); #Red for external contours _green = (0, 255, 0);# Gren internal contours levels=2 #1 contours drawn, 2 internal contours as well, 3 ... cv.DrawContours (orig, contours, _red, _green, levels, 2, cv.CV_FILLED) #Draw contours on the colour image cv.ShowImage("Image", orig) cv.WaitKey(0)
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
# coding:UTF-8 import cv2 from src import App img_file = App.resource_file("/opencv/timg.jpg") im = cv2.imread(img_file, 0) sobx = cv2.CreateImage(cv2.GetSize(im), cv2.IPL_DEPTH_16S, 1) #Sobel with x-order=1 cv2.Sobel(im, sobx, 1, 0, 3) soby = cv2.CreateImage(cv2.GetSize(im), cv2.IPL_DEPTH_16S, 1) #Sobel withy-oder=1 cv2.Sobel(im, soby, 0, 1, 3) cv2.Abs(sobx, sobx) cv2.Abs(soby, soby) result = cv2.CloneImage(im) #Add the two results together. cv2.Add(sobx, soby, result) cv2.Threshold(result, result, 100, 255, cv2.CV_THRESH_BINARY_INV) cv2.ShowImage('Image', im) cv2.ShowImage('Result', result) cv2.WaitKey(0)
def process_image(self, slider_pos): global cimg, source_image1, ellipse_size, maxf, maxs, eoc, lastcx,lastcy,lastr """ This function finds contours, draws them and their approximation by ellipses. """ stor = cv.CreateMemStorage() # Create the destination images cimg = cv.CloneImage(self.source_image) cv.Zero(cimg) image02 = cv.CloneImage(self.source_image) cv.Zero(image02) image04 = cv.CreateImage(cv.GetSize(self.source_image), cv.IPL_DEPTH_8U, 3) cv.Zero(image04) # Threshold the source image. This needful for cv.FindContours(). cv.Threshold(self.source_image, image02, slider_pos, 255, cv.CV_THRESH_BINARY) # Find all contours. cont = cv.FindContours(image02, stor, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_NONE, (0, 0)) maxf = 0 maxs = 0 size1 = 0 for c in contour_iterator(cont): if len(c) > ellipse_size: PointArray2D32f = cv.CreateMat(1, len(c), cv.CV_32FC2) for (i, (x, y)) in enumerate(c): PointArray2D32f[0, i] = (x, y) # Draw the current contour in gray gray = cv.CV_RGB(100, 100, 100) cv.DrawContours(image04, c, gray, gray,0,1,8,(0,0)) if iter == 0: strng = segF + '/' + 'contour1.png' cv.SaveImage(strng,image04) color = (255,255,255) (center, size, angle) = cv.FitEllipse2(PointArray2D32f) # Convert ellipse data from float to integer representation. center = (cv.Round(center[0]), cv.Round(center[1])) size = (cv.Round(size[0] * 0.5), cv.Round(size[1] * 0.5)) if iter == 1: if size[0] > size[1]: size2 = size[0] else: size2 = size[1] if size2 > size1: size1 = size2 size3 = size # Fits ellipse to current contour. if eoc == 0 and iter == 2: rand_val = abs((lastr - ((size[0]+size[1])/2))) if rand_val > 20 and float(max(size[0],size[1]))/float(min(size[0],size[1])) < 1.5: lastcx = center[0] lastcy = center[1] lastr = (size[0]+size[1])/2 if rand_val > 20 and float(max(size[0],size[1]))/float(min(size[0],size[1])) < 1.4: cv.Ellipse(cimg, center, size, angle, 0, 360, color,2, cv.CV_AA, 0) cv.Ellipse(source_image1, center, size, angle, 0, 360, color,2, cv.CV_AA, 0) elif eoc == 1 and iter == 2: (int,cntr,rad) = cv.MinEnclosingCircle(PointArray2D32f) cntr = (cv.Round(cntr[0]), cv.Round(cntr[1])) rad = (cv.Round(rad)) if maxf == 0 and maxs == 0: cv.Circle(cimg, cntr, rad, color, 1, cv.CV_AA, shift=0) cv.Circle(source_image1, cntr, rad, color, 2, cv.CV_AA, shift=0) maxf = rad elif (maxf > 0 and maxs == 0) and abs(rad - maxf) > 30: cv.Circle(cimg, cntr, rad, color, 2, cv.CV_AA, shift=0) cv.Circle(source_image1, cntr, rad, color, 2, cv.CV_AA, shift=0) maxs = len(c) if iter == 1: temp3 = 2*abs(size3[1] - size3[0]) if (temp3 > 40): eoc = 1
def Dilation(pos): element = cv.CreateStructuringElementEx(pos * 2 + 1, pos * 2 + 1, pos, pos, element_shape) cv.Dilate(src, dest, element, 1) cv.ShowImage("Erosion & Dilation", dest) if __name__ == "__main__": if len(sys.argv) > 1: src = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR) else: url = 'https://code.ros.org/svn/opencv/trunk/opencv/samples/c/fruits.jpg' filedata = urllib2.urlopen(url).read() imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1) cv.SetData(imagefiledata, filedata, len(filedata)) src = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR) image = cv.CloneImage(src) dest = cv.CloneImage(src) cv.NamedWindow("Opening & Closing", 1) cv.NamedWindow("Erosion & Dilation", 1) cv.ShowImage("Opening & Closing", src) cv.ShowImage("Erosion & Dilation", src) cv.CreateTrackbar("Open", "Opening & Closing", 0, 10, Opening) cv.CreateTrackbar("Close", "Opening & Closing", 0, 10, Closing) cv.CreateTrackbar("Dilate", "Erosion & Dilation", 0, 10, Dilation) cv.CreateTrackbar("Erode", "Erosion & Dilation", 0, 10, Erosion) cv.WaitKey(0) cv.DestroyWindow("Opening & Closing") cv.DestroyWindow("Erosion & Dilation")
def CamGui(): capture = cv.VideoCapture(0) width = int(capture.get(cv.CAP_PROP_FRAME_WIDTH)) height = int(capture.get(cv.CAP_PROP_FRAME_HEIGHT)) prev_gray = cv.CreateImage((width, height), 8, 1) gray = cv.CreateImage((width, height), 8, 1) # Will hold the pyr frame at t-1 prevPyr = cv.CreateImage((height / 3, width + 8), 8, cv.CV_8UC1) currPyr = cv.CreateImage((height / 3, width + 8), 8, cv.CV_8UC1) # idem at t max_count = 500 qLevel = 0.01 minDist = 10 prev_points = [] # Points at t-1 curr_points = [] # Points at t lines = [] # To keep all the lines overtime while True: frame = cv.QueryFrame(capture) cv.CvtColor(frame, gray, cv.CV_BGR2GRAY) # Convert to gray output = cv.CloneImage(frame) prev_points = cv.GoodFeaturesToTrack( gray, None, None, max_count, qLevel, minDist) curr_points, status, err = cv.CalcOpticalFlowPyrLK( prev_gray, gray, prevPyr, currPyr, prev_points, (10, 10), 3, (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 20, 0.03), 0) # If points status are ok and distance not negligible keep the point k = 0 for i in range(len(curr_points)): nb = abs(int(prev_points[i][0]) - int(curr_points[i][0])) + \ abs(int(prev_points[i][1]) - int(curr_points[i][1])) if status[i] and nb > 2: prev_points[k] = prev_points[i] curr_points[k] = curr_points[i] k += 1 prev_points = prev_points[:k] curr_points = curr_points[:k] # At the end only interesting points are kept # Draw all the previously kept lines otherwise they would be lost the next frame for (pt1, pt2) in lines: cv.Line(frame, pt1, pt2, (255, 255, 255)) # Draw the lines between each points at t-1 and t for prevpoint, point in zip(prev_points, curr_points): prevpoint = (int(prevpoint[0]), int(prevpoint[1])) cv.Circle(frame, prevpoint, 15, 0) point = (int(point[0]), int(point[1])) cv.Circle(frame, point, 3, 255) cv.Line(frame, prevpoint, point, (255, 255, 255)) # Append current lines to the lines list lines.append((prevpoint, point)) cv.Copy(gray, prev_gray) # Put the current frame prev_gray prev_points = curr_points cv.ShowImage("The Video", frame) #cv.WriteFrame(writer, frame) c = cv.WaitKey(1) if c == 27: # Esc on Windows break