def draw_circles(storage, output): circles = np.asarray(storage) print len(circles), 'circles found' for circle in circles: Radius, x, y = int(circle[0][2]), int(circle[0][0]), int(circle[0][1]) cv2.Circle(output, (x, y), 1, cv2.RGB(0, 255, 0), -1, 8, 0) cv2.Circle(output, (x, y), Radius, cv2.RGB(255, 0, 0), 3, 8, 0)
def draw_phase(self, frame, phase): x, y, w, h = self.metrics c = self.get_colour() x -= int(Annotator.PULSE_SIZE[1] * 1.5) y -= Annotator.PULSE_SIZE[1] if (phase % (2.0 * numpy.pi)) < Annotator.PULSE_PHASE: radius = Annotator.PULSE_SIZE[1] else: radius = Annotator.PULSE_SIZE[0] cv.Circle(frame, (x, y), radius + Annotator.BORDER, c[1], -1) cv.Circle(frame, (x, y), radius, c[0], -1)
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 show_keypoints(data): """ paint and show images with keypoints""" for i in range(len(data)): try: if data[i].facedata: for j in range(len(data[i].facedata)): nbr_keypoints = len(data[i].facedata[j].keypoints) print('%d Features found in file %s' % (nbr_keypoints, data[i].filename)) tmpImage = cv.CloneMat(data[i].facedata[j].face) for k in range(nbr_keypoints): if parameter.description_method == 'sift': size = int(data[i].facedata[j].keypoints[k].size) elif parameter.description_method == 'surf': size = int( data[i].facedata[j].keypoints[k].size) / 2 cv.Circle( tmpImage, (int(data[i].facedata[j].keypoints[k].pt[0]), int(data[i].facedata[j].keypoints[k].pt[1])), size, 255) show_images(tmpImage) except: logging.error( 'Error showing keypoints - Maybe no Face in File %s (tools.py)' % data[i].filename)
def show_shapes(shapes): """ Function to show all of the shapes which are passed to it """ cv.NamedWindow("Shape Model", cv.CV_WINDOW_AUTOSIZE) # Get size for the window max_x = int(max([pt.x for shape in shapes for pt in shape.pts])) max_y = int(max([pt.y for shape in shapes for pt in shape.pts])) min_x = int(min([pt.x for shape in shapes for pt in shape.pts])) min_y = int(min([pt.y for shape in shapes for pt in shape.pts])) i = cv.CreateImage((max_x-min_x+20, max_y-min_y+20), cv.IPL_DEPTH_8U, 3) cv.Set(i, (0, 0, 0)) for shape in shapes: r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) #r = 0 #g = 0 #b = 0 for pt_num, pt in enumerate(shape.pts): # Draw normals #norm = shape.get_normal_to_point(pt_num) #cv.Line(i,(pt.x-min_x,pt.y-min_y), \ # (norm[0]*10 + pt.x-min_x, norm[1]*10 + pt.y-min_y), (r, g, b)) cv.Circle(i, (int(pt.x-min_x), int(pt.y-min_y)), 2, (r, g, b), -1) cv.ShowImage("Shape Model",i)
def draw_model_fitter(f): cv.NamedWindow("Model Fitter", cv.CV_WINDOW_AUTOSIZE) # Copy image i = cv.CreateImage(cv.GetSize(f.image), f.image.depth, 3) cv.Copy(f.image, i) for pt_num, pt in enumerate(f.shape.pts): # Draw normals cv.Circle(i, (int(pt.x), int(pt.y)), 2, (0,0,0), -1) cv.ShowImage("Shape Model",i) cv.WaitKey()
def draw_y_by_t(self): width = 700 height = 700 canvas = np.array((300, 300), np.uint8) i = 0 for pos in positions[-self.window_sz:]: x = int(width * (i + 1) / (self.window_sz + 1)) y = pos[1] cv2.Circle(canvas, pos, (120, 150, 200), 6) return canvas
def run(self): while True: img = self.capture.read() #blur the source image to reduce color noise cv2.blur(img, img, 3) #convert the image to hsv(Hue, Saturation, Value) so its #easier to determine the color to track(hue) hsv_img = cv2.CreateImage(cv2.GetSize(img), 8, 3) cv2.CvtColor(img, hsv_img, cv2.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 greenLower = (20, 190, 165) greenUpper = (30, 225, 220) thresholded_img = cv2.CreateImage(cv2.GetSize(hsv_img), 8, 1) cv2.InRangeS(hsv_img, greenLower, greenUpper, thresholded_img) #determine the objects moments and check that the area is large #enough to be our object moments = cv2.Moments(thresholded_img, 0) area = cv2.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 = cv2.GetSpatialMoment(moments, 1, 0) / area y = cv2.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 = cv2.CreateImage(cv2.GetSize(img), 8, 3) cv2.Circle(overlay, (x, y), 2, (255, 255, 255), 20) cv2.Add(img, overlay, img) #add the thresholded image back to the img so we can see what was #left after it was applied cv2.Merge(thresholded_img, None, None, None, img) #display the image cv2.ShowImage(color_tracker_window, img) if cv2.WaitKey(10) == 27: break
def run(self): #initiate font font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) # instantiate images hsv_img = cv.CreateImage(cv.GetSize(cv.QueryFrame(self.capture)), 8, 3) threshold_img1 = cv.CreateImage(cv.GetSize(hsv_img), 8, 1) threshold_img1a = cv.CreateImage(cv.GetSize(hsv_img), 8, 1) threshold_img2 = cv.CreateImage(cv.GetSize(hsv_img), 8, 1) i = 0 writer = cv.CreateVideoWriter('angle_tracking.avi', cv.CV_FOURCC('M', 'J', 'P', 'G'), 30, cv.GetSize(hsv_img), 1) while True: # capture the image from the cam img = cv.QueryFrame(self.capture) # convert the image to HSV cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV) # threshold the image to isolate two colors cv.InRangeS(hsv_img, (165, 145, 100), (250, 210, 160), threshold_img1) # red cv.InRangeS(hsv_img, (0, 145, 100), (10, 210, 160), threshold_img1a) # red again cv.Add(threshold_img1, threshold_img1a, threshold_img1) # this is combining the two limits for red cv.InRangeS(hsv_img, (105, 180, 40), (120, 260, 100), threshold_img2) # blue # determine the moments of the two objects threshold_img1 = cv.GetMat(threshold_img1) threshold_img2 = cv.GetMat(threshold_img2) moments1 = cv.Moments(threshold_img1, 0) moments2 = cv.Moments(threshold_img2, 0) area1 = cv.GetCentralMoment(moments1, 0, 0) area2 = cv.GetCentralMoment(moments2, 0, 0) # initialize x and y x1, y1, x2, y2 = (1, 2, 3, 4) coord_list = [x1, y1, x2, y2] for x in coord_list: x = 0 # there can be noise in the video so ignore objects with small areas if (area1 > 200000): # x and y coordinates of the center of the object is found by dividing the 1,0 and 0,1 moments by the area x1 = int(cv.GetSpatialMoment(moments1, 1, 0) / area1) y1 = int(cv.GetSpatialMoment(moments1, 0, 1) / area1) # draw circle cv.Circle(img, (x1, y1), 2, (0, 255, 0), 20) # write x and y position cv.PutText(img, str(x1) +', '+str(y1), (x1, y1 + 20), font, 255) # Draw the text if (area2 > 100000): # x and y coordinates of the center of the object is found by dividing the 1,0 and 0,1 moments by the area x2 = int(cv.GetSpatialMoment(moments2, 1, 0) / area2) y2 = int(cv.GetSpatialMoment(moments2, 0, 1) / area2) # draw circle cv.Circle(img, (x2, y2), 2, (0, 255, 0), 20) cv.PutText(img, str(x2) +', '+str(y2), (x2, y2 + 20), font, 255) # Draw the text cv.Line(img, (x1, y1), (x2, y2), (0, 255, 0), 4, cv.CV_AA) # draw line and angle cv.Line(img, (x1, y1), (cv.GetSize(img)[0], y1), (100, 100, 100, 100), 4, cv.CV_AA) x1 = float(x1) y1 = float(y1) x2 = float(x2) y2 = float(y2) angle = int(math.atan((y1 - y2) / (x2 - x1)) * 180 / math.pi) cv.PutText(img, str(angle), (int(x1) + 50, (int(y2) + int(y1)) / 2), font, 255) # cv.WriteFrame(writer,img) # display frames to users cv.ShowImage('Target', img) cv.ShowImage('Threshold1', threshold_img1) cv.ShowImage('Threshold2', threshold_img2) cv.ShowImage('hsv', hsv_img) # Listen for ESC or ENTER key c = cv.WaitKey(7) % 0x100 if c == 27 or c == 10: break cv.DestroyAllWindows()
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
feat=cv.goodFeaturesToTrack(prev_gray, mask=None, **shi_param) mask=np.zeros_like(frame) while(cap.isOpened()): ret, frame=cv.read() gray_frame=cv.cvtColor(frame,cv.COLOR_BGR2GRAY) next, status, error = cv.calcOpticalFlowPyrLK(gray_frame,feat,mask=None, **lucas_kanade_param) good_old=prev[status==1] good_new=next[status==1] for i,(new,old) in enumerate(zip(good_new,good_new)): a,b = new.ravel() c,d = old.ravel() mask=cv.line(mask, (a,b), (c,d), color, 2) frame = cv.Circle(frame, (a,b), (c,d), 3, color, -1) output=cv.add(frame,mask) prev_gray=gray.copy() cv.imshow("optical flow",output) if cv.waitKey(1) & 0xFF == ord("q"): break cap.release() cv.destroyAllWindows()
import copy import numpy as np import cv2 int R = 53 int snr = 5200 imgIn = cv2.imread("original.jpg",0) // it needs to process even image only //Rect roi = Rect(0, 0, imgIn.cols & -2, imgIn.rows & -2); roi = imgIn[0:(imgIn.shape[0] & -2), 0:(imgIn.shape[1] & -2)] //Hw calculation (start) //calcPSF(h, roi.shape, R); outputImg = h,filterSize = roi //Mat h(filterSize, CV_32F, Scalar(0)); center = (filterSize.shape[1] / 2, filterSize.shape[0] / 2) cv2.Circle(h, center, R, color = 255, thickness=1, lineType=8, shift=0) summa = np.sum(h); outputImg = h / summa[0]; #----------------------------------------------------------------------------------------------------- #calcWnrFilter(h, Hw, 1.0 / double(snr)); input_h_PSF = h output_G = Hw nsr = 1.0/float(snr) #--------------------------------------------------------------- #fftshift(input_h_PSF, h_PSF_shifted); inputImg = input_h_PSF outputImg = inputImg; cx = outputImg.shape[0] / 2 cy = outputImg.shape[1] / 2 q0 = outputImg[0:cx, 0:cy] # Top-Left - Create a ROI per quadrant q1 = outputImg[cx:cx+cx, 0:cy] # Top-Right q2 = outputImg[0:cx, cy:cy+cy] # Bottom-Left
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
def draw_circles(storage, output): circles = np.asarray(storage) for circle in circles: Radius, x, y = int(circle[0][3]), int(circle[0][0]), int(circle[0][4]) cv2.Circle(output, (x, y), 1, cv2.RGB(0, 255, 0), -1, 8, 0) cv2.Circle(output, (x, y), Radius, cv2.RGB(255, 0, 0), 3, 8, 0)