def findImageContour(img, frame): storage = cv.CreateMemStorage() cont = cv.FindContours(img, storage, cv.CV_RETR_EXTERNAL, cv.CV_CHAIN_APPROX_NONE, (0, 0)) max_center = [None, 0] for c in contour_iterator(cont): # Number of points must be more than or equal to 6 for cv.FitEllipse2 # Use to set minimum size of object to be tracked. if len(c) >= 60: # Copy the contour into an array of (x,y)s PointArray2D32f = cv.CreateMat(1, len(c), cv.CV_32FC2) for (i, (x, y)) in enumerate(c): PointArray2D32f[0, i] = (x, y) # Fits ellipse to current contour. (center, size, angle) = cv.FitEllipse2(PointArray2D32f) # Only consider location of biggest contour -- adapt for multiple object tracking if size > max_center[1]: max_center[0] = center max_center[1] = size angle = angle if True: # Draw the current contour in gray gray = cv.CV_RGB(255, 255, 255) cv.DrawContours(img, c, gray, gray, 0, 1, 8, (0, 0)) if max_center[1] > 0: # Convert ellipse data from float to integer representation. center = (cv.Round(max_center[0][0]), cv.Round(max_center[0][1])) size = (cv.Round(max_center[1][0] * 0.5), cv.Round(max_center[1][1] * 0.5)) color = cv.CV_RGB(255, 0, 0) cv.Ellipse(frame, center, size, angle, 0, 360, color, 3, cv.CV_AA, 0)
def detect_and_draw(img, face_cascade): gray = cv.CreateImage((img.width, img.height), 8, 1) image_scale = img.width / smallwidth small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # gray = cv.CreateImage((img.width,img.height), 8, 1) image_scale = img.width / smallwidth # small_img = cv.CreateImage((cv.Round(img.width / image_scale), cv.Round (img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) faces = cv.HaarDetectObjects(small_img, face_cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) if opencv_preview and faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) if verbose: print "Face at: ", pt1[0], ",", pt2[0], "\t", pt1[1], ",", pt2[ 1] return True if faces else False
def detect_face(self, image): min_size = (20, 20) image_scale = 2 haar_scale = 1.1 min_neighbors = 2 haar_flags = 0 # Allocate the temporary images gray = cv.CreateImage((image.width, image.height), 8, 1) smallImage = cv.CreateImage((cv.Round( image.width / image_scale), cv.Round(image.height / image_scale)), 8, 1) # Convert color input image to grayscale cv.CvtColor(image, gray, cv.CV_BGR2GRAY) # Scale input image for faster processing cv.Resize(gray, smallImage, cv.CV_INTER_LINEAR) # Equalize the histogram cv.EqualizeHist(smallImage, smallImage) # Detect the faces faces = cv.HaarDetectObjects(smallImage, self.cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) return faces
def detectFace(img, cascade): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage( (cv.Round(img.width / imageScale), cv.Round(img.height / imageScale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haarScale, minNeighbors, haarFlags, minSize) if faces: print "\tDetected ", len(faces), " object(s)" for ((x, y, w, h), n) in faces: #the input to cv.HaarDetectObjects was resized, scale the #bounding box of each face and convert it to two CvPoints pt1 = (int(x * imageScale), int(y * imageScale)) pt2 = (int((x + w) * imageScale), int((y + h) * imageScale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) return img else: return False
def detect_and_draw(img, cascade): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round(img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if(cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t print "detection time = %gms" % (t / (cv.GetTickFrequency() * 1000.)) if faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) cv.ShowImage("result", img)
def draw_subdiv_facet(img, edge): t = edge count = 0 # count number of edges in facet while count == 0 or t != edge: count += 1 t = cv.Subdiv2DGetEdge(t, cv.CV_NEXT_AROUND_LEFT) buf = [] # gather points t = edge for i in range(count): assert t > 4 pt = cv.Subdiv2DEdgeOrg(t) if not pt: break buf.append((cv.Round(pt.pt[0]), cv.Round(pt.pt[1]))) t = cv.Subdiv2DGetEdge(t, cv.CV_NEXT_AROUND_LEFT) if (len(buf) == count): pt = cv.Subdiv2DEdgeDst(cv.Subdiv2DRotateEdge(edge, 1)) cv.FillConvexPoly( img, buf, cv.RGB(random.randrange(256), random.randrange(256), random.randrange(256)), cv.CV_AA, 0) cv.PolyLine(img, [buf], 1, cv.RGB(0, 0, 0), 1, cv.CV_AA, 0) draw_subdiv_point(img, pt.pt, cv.RGB(0, 0, 0))
def detect_and_draw(self, img, cascade, camera_position=0): min_size = (20, 20) image_scale = self.horizontalSlider_3.value() haar_scale = 1.2 min_neighbors = 2 haar_flags = 0 # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img_height = cv.Round(img.height / image_scale) small_img = cv.CreateImage( (cv.Round(img.width / image_scale), small_img_height), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) if faces: for ((x, y, w, h), n) in faces: if self.face_cert < n: x2, y2, w2, h2 = self.make_the_rectangle_bigger( x, y, w, h, 1.22, small_img_height, image_scale) self.create_person_and_add_to_room(img, (x2, y2, w2, h2), camera_position) if self.mark_detected_objects[camera_position]: pt2 = (int(x2 + w2), int(y2 + h2)) cv.Rectangle(img, (x2, y2), pt2, cv.RGB(255, 0, 0), 3, 8, 0) if self.show_main_view[camera_position]: cv.ShowImage("result" + str(camera_position), img)
def detect_and_draw(img, cascade, jpg_cnt): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if (cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t print "detection time = %gms" % (t / (cv.GetTickFrequency() * 10000)) if faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) if jpg_cnt % 50 == 1: print('capture completed') cv.SaveImage('test_' + str(jpg_cnt) + '.jpg', img) print("aaa1") url = 'http://210.94.185.52:8080/upload.php' #files={ 'upfiles' : open('/home/lee/test_'+str(jpg_cnt)+'.jpg','rb')} files = { 'upfiles': open('/home/lee/test_' + str(jpg_cnt) + '.jpg', 'rb') } print("aaa2") r = requests.post(url, files=files) print("aaa3") print(r.text) for i in r.text.split(): try: op = float(i) break except: continue print(op) #LED if op >= 0.9: lock_on() else: print('no') cv.ShowImage("result", img)
def update_mhi(img, dst, diff_threshold): global last global mhi global storage global mask global orient global segmask timestamp = time.clock() / CLOCKS_PER_SEC # get current time in seconds size = cv.GetSize(img) # get current frame size idx1 = last if not mhi or cv.GetSize(mhi) != size: for i in range(N): buf[i] = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1) cv.Zero(buf[i]) mhi = cv.CreateImage(size,cv. IPL_DEPTH_32F, 1) cv.Zero(mhi) # clear MHI at the beginning orient = cv.CreateImage(size,cv. IPL_DEPTH_32F, 1) segmask = cv.CreateImage(size,cv. IPL_DEPTH_32F, 1) mask = cv.CreateImage(size,cv. IPL_DEPTH_8U, 1) cv.CvtColor(img, buf[last], cv.CV_BGR2GRAY) # convert frame to grayscale idx2 = (last + 1) % N # index of (last - (N-1))th frame last = idx2 silh = buf[idx2] cv.AbsDiff(buf[idx1], buf[idx2], silh) # get difference between frames cv.Threshold(silh, silh, diff_threshold, 1, cv.CV_THRESH_BINARY) # and threshold it cv.UpdateMotionHistory(silh, mhi, timestamp, MHI_DURATION) # update MHI cv.CvtScale(mhi, mask, 255./MHI_DURATION, (MHI_DURATION - timestamp)*255./MHI_DURATION) cv.Zero(dst) cv.Merge(mask, None, None, None, dst) cv.CalcMotionGradient(mhi, mask, orient, MAX_TIME_DELTA, MIN_TIME_DELTA, 3) if not storage: storage = cv.CreateMemStorage(0) seq = cv.SegmentMotion(mhi, segmask, storage, timestamp, MAX_TIME_DELTA) for (area, value, comp_rect) in seq: if comp_rect[2] + comp_rect[3] > 100: # reject very small components color = cv.CV_RGB(255, 0,0) silh_roi = cv.GetSubRect(silh, comp_rect) mhi_roi = cv.GetSubRect(mhi, comp_rect) orient_roi = cv.GetSubRect(orient, comp_rect) mask_roi = cv.GetSubRect(mask, comp_rect) angle = 360 - cv.CalcGlobalOrientation(orient_roi, mask_roi, mhi_roi, timestamp, MHI_DURATION) count = cv.Norm(silh_roi, None, cv.CV_L1, None) # calculate number of points within silhouette ROI if count < (comp_rect[2] * comp_rect[3] * 0.05): continue magnitude = 30. center = ((comp_rect[0] + comp_rect[2] / 2), (comp_rect[1] + comp_rect[3] / 2)) cv.Circle(dst, center, cv.Round(magnitude*1.2), color, 3, cv.CV_AA, 0) cv.Line(dst, center, (cv.Round(center[0] + magnitude * cos(angle * cv.CV_PI / 180)), cv.Round(center[1] - magnitude * sin(angle * cv.CV_PI / 180))), color, 3, cv.CV_AA, 0)
def track(img, threshold=100): '''Accepts BGR image and optional object threshold between 0 and 255 (default = 100). Returns: (x,y) coordinates of centroid if found (-1,-1) if no centroid was found None if user hit ESC ''' cascade = cv.Load("haarcascade_frontalface_default.xml") gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) center = (-1, -1) faces = [] original_size_faces = [] #import ipdb; ipdb.set_trace() if (cascade): t = cv.GetTickCount() # HaarDetectObjects takes 0.02s faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t if faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) # cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) #cv.Rectangle(img, (x,y), (x+w,y+h), 255) # get the xy corner co-ords, calc the center location x1 = pt1[0] x2 = pt2[0] y1 = pt1[1] y2 = pt2[1] centerx = x1 + ((x2 - x1) / 2) centery = y1 + ((y2 - y1) / 2) center = (centerx, centery) scaled = ((x1, y1, x2 - x1, y2 - y1), n) original_size_faces.append(scaled) # print scaled # cv.NamedWindow(WINDOW_NAME, 1) # cv.ShowImage(WINDOW_NAME, img) # if cv.WaitKey(5) == 27: # center = None return (center, original_size_faces)
def draw_Lines(lines, img): for (rho, theta) in lines[:5]: a = cos(theta) b = sin(theta) x0 = a * rho y0 = b * rho pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a))) pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a))) cv.Line(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8)
def lines2(): im = cv.LoadImage('roi_edges.jpg', cv.CV_LOAD_IMAGE_GRAYSCALE) pi = math.pi x = 0 dst = cv.CreateImage(cv.GetSize(im), 8, 1) cv.Canny(im, dst, 200, 200) cv.Threshold(dst, dst, 100, 255, cv.CV_THRESH_BINARY) color_dst_standard = cv.CreateImage(cv.GetSize(im), 8, 3) cv.CvtColor(im, color_dst_standard, cv.CV_GRAY2BGR) #Create output image in RGB to put red lines lines = cv.HoughLines2(dst, cv.CreateMemStorage(0), cv.CV_HOUGH_STANDARD, 1, pi / 100, 71, 0, 0) klsum = 0 klaver = 0 krsum = 0 kraver = 0 #global k #k=0 for (rho, theta) in lines[:100]: kl = [] kr = [] a = math.cos(theta) b = math.sin(theta) x0 = a * rho y0 = b * rho pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a))) pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a))) k = ((y0 - 1000 * (a)) - (y0 + 1000 * (a))) / ((x0 - 1000 * (-b)) - (x0 + 1000 * (-b))) if abs(k) < 0.4: pass elif k > 0: kr.append(k) len_kr = len(kr) for i in kr: krsum = krsum + i kraver = krsum / len_kr cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4) elif k < 0: kr.append(k) kl.append(k) len_kl = len(kl) for i in kl: klsum = klsum + i klaver = klsum / len_kl cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4) #print k # cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4) cv.SaveImage('lane.jpg', color_dst_standard) print '左车道平均斜率:', klaver, ' 右车道平均斜率:', kraver cv.ShowImage("Hough Standard", color_dst_standard) cv.WaitKey(0)
def DetectRedEyes(image, faceCascade, eyeCascade): min_size = (20,20) image_scale = 2 haar_scale = 1.2 min_neighbors = 2 haar_flags = 0 # Allocate the temporary images gray = cv.CreateImage((image.width, image.height), 8, 1) smallImage = cv.CreateImage((cv.Round(image.width / image_scale),cv.Round (image.height / image_scale)), 8 ,1) # Convert color input image to grayscale cv.CvtColor(image, gray, cv.CV_BGR2GRAY) # Scale input image for faster processing cv.Resize(gray, smallImage, cv.CV_INTER_LINEAR) # Equalize the histogram cv.EqualizeHist(smallImage, smallImage) # Detect the faces faces = cv.HaarDetectObjects(smallImage, faceCascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) # If faces are found if faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(image, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) face_region = cv.GetSubRect(image,(x,int(y + (h/4)),w,int(h/2))) cv.SetImageROI(image, (pt1[0], pt1[1], pt2[0] - pt1[0], int((pt2[1] - pt1[1]) * 0.7))) eyes = cv.HaarDetectObjects(image, eyeCascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, (15,15)) if eyes: # For each eye found for eye in eyes: # Draw a rectangle around the eye cv.Rectangle(image, (eye[0][0], eye[0][1]), (eye[0][0] + eye[0][2], eye[0][1] + eye[0][3]), cv.RGB(255, 0, 0), 1, 8, 0) cv.ResetImageROI(image) return image
def detect_and_draw(img, cascade, detected): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) image_scale = img.width / smallwidth small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if (cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) # t = cv.GetTickCount() - t # print "detection time = %gms" % (t/(cv.GetTickFrequency()*1000.)) if faces: if detected == 0: # os.system('festival --tts hi &') detected = 1 for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) print "Face at: ", pt1[0], ",", pt2[0], "\t", pt1[1], ",", pt2[ 1] # find amount needed to pan/tilt span = (pt1[0] + pt2[0]) / 2 stlt = (pt1[1] + pt2[1]) / 2 mid = smallwidth / 2 if span < mid: print "left", mid - span else: print "right", span - mid #os.system('echo "6="' + str(valTilt) + ' > /dev/pi-blaster') #os.system('echo "7="' + str(valPan) + ' > /dev/pi-blaster') else: if detected == 1: #print "Last seen at: ", pt1[0], ",", pt2[0], "\t", pt1[1], ",", pt2[1] #os.system('festival --tts bye &') status = "just disappeared" detected = 0 cv.ShowImage("result", img) return detected
def OnPaint(self, evt): if not self.timer.IsRunning() : dc = wx.BufferedDC(wx.ClientDC(self), wx.NullBitmap, wx.BUFFER_VIRTUAL_AREA) dc.SetBackground(wx.Brush(wx.Colour(0, 0, 0))) return # Capture de l'image frame = cv.QueryFrame(CAMERA) cv.CvtColor(frame, frame, cv.CV_BGR2RGB) Img = wx.EmptyImage(frame.width, frame.height) Img.SetData(frame.tostring()) self.bmp = wx.BitmapFromImage(Img) width, height = frame.width, frame.height # Détection des visages min_size = (20, 20) image_scale = 2 haar_scale = 1.2 min_neighbors = 2 haar_flags = 0 gray = cv.CreateImage((frame.width, frame.height), 8, 1) small_img = cv.CreateImage((cv.Round(frame.width / image_scale), cv.Round (frame.height / image_scale)), 8, 1) cv.CvtColor(frame, gray, cv.CV_BGR2GRAY) cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) listeVisages = cv.HaarDetectObjects(small_img, CASCADE, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) # Affichage de l'image x, y = (0, 0) try: dc = wx.BufferedDC(wx.ClientDC(self), wx.NullBitmap, wx.BUFFER_VIRTUAL_AREA) try : dc.SetBackground(wx.Brush(wx.Colour(0, 0, 0))) except : pass dc.Clear() dc.DrawBitmap(self.bmp, x, y) # Dessin des rectangles des visages if listeVisages : for ((x, y, w, h), n) in listeVisages : dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(wx.Pen(wx.Colour(255, 0, 0), 2)) dc.DrawRectangle(x* image_scale, y* image_scale, w* image_scale, h* image_scale) self.listeVisages = listeVisages del dc del Img except TypeError: pass except wx.PyDeadObjectError: pass
def detect_and_draw(img, cascade): # allocate temporary images gray = cv.CreateImage((img.width,img.height), 8, 1) small_img = cv.CreateImage((cv.Round(img.width / image_scale), cv.Round (img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if(cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t #print "detection time = %gms" % (t/(cv.GetTickFrequency()*1000.)) if faces: count = 0 stop = 1 name = 1 no = 1 dict = {} for num in range(14): dict[name] = no name += 1 print dict f = open('no.json','w') json.dump(dict,f) #for count in range(14): #time.sleep(stop) #count += 1 #print(count) #time.sleep(stop) #cv.PutText(img, "SAMPLE_TEXT", (0, 50), cv.CV_FONT_HERSHEY_PLAIN, cv.RGB(255, 255, 255)) #cv.PutText(img, "SAMPLE_TEXT", (0, 50), cv.CV_FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 2, cv.CV_AA ) for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints #for count in range(14): count += 1 print(count) pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) #count = count + 1 #print(count) # cv.putText(img, "SAMPLE_TEXT", (0, 50), FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 2, cv.CV_AA) cv.ShowImage("result", img)
def detect_and_draw(img, cascade, c): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) face_flag = False if (cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t print "detection time = %gms" % (t / (cv.GetTickFrequency() * 1000.)) if faces: face_flag = True for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) # ある程度顔が検出されたら if c > 4: # 画像の保存 global counter counter = -1 d = datetime.today() datestr = d.strftime('%Y-%m-%d_%H-%M-%S') outputname = '/home/pi/fd/fd_' + datestr + '.jpg' cv.SaveImage(outputname, img) print 'Face Detect' # 読み込みと切り取り fimg = cv.LoadImage(outputname) fimg_trim = fimg[pt1[1]:pt2[1], pt1[0]:pt2[0]] outputname2 = '/home/pi/fd/face_' + datestr + '.jpg' cv.SaveImage(outputname2, fimg_trim) print 'Face Image Save' cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) cv.ShowImage("result", img) return face_flag
def DetectRedEyes(image, faceCascade): min_size = (20, 20) image_scale = 2 haar_scale = 1.1 min_neighbors = 2 haar_flags = 0 # Allocate the temporary images gray = cv.CreateImage((image.width, image.height), 8, 1) smallImage = cv.CreateImage((cv.Round( image.width / image_scale), cv.Round(image.height / image_scale)), 8, 1) # Convert color input image to grayscale cv.CvtColor(image, gray, cv.CV_BGR2GRAY) # Scale input image for faster processing cv.Resize(gray, smallImage, cv.CV_INTER_LINEAR) # Equalize the histogram cv.EqualizeHist(smallImage, smallImage) # Detect the faces faces = cv.HaarDetectObjects(smallImage, faceCascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) # If faces are found if faces: #print faces for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints #print "face" global line2 line2 = n pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) # print pt1 # print pt2 cv.Rectangle(image, pt1, pt2, cv.RGB(255, 0, 0), 1, 8, 0) cv.PutText(image, "face" + str(h), pt1, font, cv.RGB(255, 0, 0)) cv.PutText(image, "Come close.", (0, 20), font, cv.RGB(255, 0, 0)) cv.PutText(image, "Ensure your forehead is well lit.", (0, 40), font, cv.RGB(255, 0, 0)) cv.PutText(image, "Hit escape when done.", (0, 60), font, cv.RGB(255, 0, 0)) cv.ResetImageROI(image) return image
def draw_subdiv_edge(img, edge, color): org_pt = cv.Subdiv2DEdgeOrg(edge) dst_pt = cv.Subdiv2DEdgeDst(edge) if org_pt and dst_pt: org = org_pt.pt dst = dst_pt.pt iorg = (cv.Round(org[0]), cv.Round(org[1])) idst = (cv.Round(dst[0]), cv.Round(dst[1])) cv.Line(img, iorg, idst, color, 1, cv.CV_AA, 0)
def detect_and_draw(img, front_cascade, profile_cascade): # allocate temporary images gray = cv.CreateImage((img.width,img.height), 8, 1) small_img = cv.CreateImage((cv.Round(img.width / image_scale), cv.Round (img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if(front_cascade): # Test for frontal face faces = cv.HaarDetectObjects(small_img, front_cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) if faces: # we've detected a face return [faces, FRONTAL] # Test for profile face faces = cv.HaarDetectObjects(small_img, profile_cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) if faces: # we've detected a face return [faces, PROFILE] #t = cv.GetTickCount() - t #print "detection time = %gms" % (t/(cv.GetTickFrequency()*1000.)) #if faces: #for ((x, y, w, h), n) in faces: ## the input to cv.HaarDetectObjects was resized, so scale the ## bounding box of each face and convert it to two CvPoints #pt1 = (int(x * image_scale), int(y * image_scale)) #pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) #imgWidth, imgHeight = cv.GetSize(img) #croppedX = max(0, x*image_scale-w*image_scale/2) #croppedY = max(0, y*image_scale-h*image_scale/2) #croppedW = min(imgWidth, (2*w)*image_scale) #croppedH = min(imgHeight, (2*h)*image_scale) #imgCropped = cv.CreateImage((croppedW, croppedH), img.depth, img.nChannels) #srcRegion = cv.GetSubRect(img, (croppedX, croppedY, croppedW, croppedH)) #cv.Copy(srcRegion, imgCropped) #cv.ShowImage("cropped", imgCropped) #cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) return []
def detect_and_draw(img, cascade): # allocate temporary images gray = cv.CreateImage((img.width,img.height), 8, 1) small_img = cv.CreateImage((cv.Round(img.width / image_scale), cv.Round (img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) #gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) #cv.EqualizeHist(small_img, small_img) if(cascade): t = cv.GetTickCount()#to get the time, create memory for calculation(createMemStorage) faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t#previous time minus current time #print "detection time = %gms" % (t/(cv.GetTickFrequency()*1000.)) roi=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] ROI=['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30'] i=0 if faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) #draw rectangle (imagename,topleft,bottomright,color,size) cv.Rectangle(img,pt1,pt2,(0,230,0),1) roi[i] = img[y: y + h, x: x + w] #cv.ShowImage(ROI[i],roi[i]) cv.SaveImage("face/temp/"+ROI[i]+".png",roi[i]) i=i+1;
def process_image(self, slider_pos): """ This function finds contours, draws them and their approximation by ellipses. """ stor = cv.CreateMemStorage() # Create the destination images 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)) for c in contour_iterator(cont): # Number of points must be more than or equal to 6 for cv.FitEllipse2 if len(c) >= 6: # Copy the contour into an array of (x,y)s 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)) # Fits ellipse to current contour. (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)) # Draw ellipse in random color color = cv.CV_RGB(random.randrange(256), random.randrange(256), random.randrange(256)) cv.Ellipse(image04, center, size, angle, 0, 360, color, 2, cv.CV_AA, 0) # Show image. HighGUI use. cv.ShowImage("Result", image04)
def hs_histogram(src): # Convert to HSV hsv = cv.CreateImage(cv.GetSize(src), 8, 3) cv.CvtColor(src, hsv, cv.CV_BGR2HSV) # Extract the H and S planes h_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1) s_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1) cv.Split(hsv, h_plane, s_plane, None, None) planes = [h_plane, s_plane] h_bins = 30 s_bins = 32 hist_size = [h_bins, s_bins] # hue varies from 0 (~0 deg red) to 180 (~360 deg red again */ h_ranges = [0, 180] # saturation varies from 0 (black-gray-white) to # 255 (pure spectrum color) s_ranges = [0, 255] ranges = [h_ranges, s_ranges] scale = 10 hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1) cv.CalcHist([cv.GetImage(i) for i in planes], hist) (_, max_value, _, _) = cv.GetMinMaxHistValue(hist) hist_img = cv.CreateImage((h_bins * scale, s_bins * scale), 8, 3) for h in range(h_bins): for s in range(s_bins): bin_val = cv.QueryHistValue_2D(hist, h, s) intensity = cv.Round(bin_val * 255 / max_value) cv.Rectangle(hist_img, (h * scale, s * scale), ((h + 1) * scale - 1, (s + 1) * scale - 1), cv.RGB(intensity, intensity, intensity), cv.CV_FILLED) return hist_img
def update_brightcont(self): # The algorithm is by Werner D. Streidt # (http://visca.com/ffactory/archives/5-99/msg00021.html) if self.contrast > 0: delta = 127. * self.contrast / 100 a = 255. / (255. - delta * 2) b = a * (self.brightness - delta) else: delta = -128. * self.contrast / 100 a = (256. - delta * 2) / 255. b = a * self.brightness + delta cv.ConvertScale(self.src_image, self.dst_image, a, b) cv.ShowImage("image", self.dst_image) cv.CalcArrHist([self.dst_image], self.hist) (min_value, max_value, _, _) = cv.GetMinMaxHistValue(self.hist) cv.Scale(self.hist.bins, self.hist.bins, float(self.hist_image.height) / max_value, 0) cv.Set(self.hist_image, cv.ScalarAll(255)) bin_w = round(float(self.hist_image.width) / hist_size) for i in range(hist_size): cv.Rectangle(self.hist_image, (int(i * bin_w), self.hist_image.height), (int((i + 1) * bin_w), self.hist_image.height - cv.Round(self.hist.bins[i])), cv.ScalarAll(0), -1, 8, 0) cv.ShowImage("histogram", self.hist_image)
def predict(self, img_rgb): nrgb = self.getNormalizedRGB(img_rgb) nrgb = nrgb.reshape(img_rgb.shape[0] * img_rgb.shape[1], 3) result_mask = np.zeros((img_rgb.shape[0] * img_rgb.shape[1], 1), dtype='uint8') print nrgb.shape[0] # self.visualizeHist( self.skin_hist, self.hist_bins, "Skin hist") # self.visualizeHist( self.non_skin_hist, self.hist_bins, "non Skin hist ") # cv2.imshow('demo', nrgb) # cv2.waitKey(0) print self.range_dist print self.high_range # self.hist_bins=[250, 250] # print self.hist_bins for i in xrange(nrgb.shape[0]): #print nrgb[1][i],nrgb[1][i],self.low_range, self.high_range if nrgb[i][1] < self.low_range[0] or nrgb[i][1] > self.high_range[ 0] or nrgb[i][2] < self.low_range[1] or nrgb[i][ 2] > self.high_range[1]: result_mask[i] = 0 continue gbin = cv.Round((nrgb[i][1] - self.low_range[0]) / self.range_dist[0] * self.hist_bins[0]) rbin = cv.Round((nrgb[i][2] - self.low_range[1]) / self.range_dist[1] * self.hist_bins[1]) skin_hist_val = self.skin_hist[gbin % 50][rbin % 50] if skin_hist_val > 0: non_skin_hist_val = self.non_skin_hist[gbin % 50][rbin % 50] if non_skin_hist_val > 0: if (skin_hist_val / non_skin_hist_val) > self.theta_thresh: result_mask[i] = 255 else: result_mask[i] = 0 else: result_mask[i] = 0 else: result_mask[i] = 0 output_mask = result_mask print cv2.countNonZero(output_mask) # print output_mask.shape output_mask = output_mask.reshape((img_rgb.shape[0], img_rgb.shape[1])) return output_mask
def detect_and_draw(img, cascade): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if (cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t print "detection time = %gms" % (t / (cv.GetTickFrequency() * 1000.)) if faces: facenum = 0 for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) #code copied from https://github.com/mitchtech/py_servo_facetracker/blob/master/facetracker_servo_gpio.py x1 = pt1[0] x2 = pt2[0] y1 = pt1[1] y2 = pt2[1] midFaceX = x1 + ((x2 - x1) / 2) midFaceY = y1 + ((y2 - y1) / 2) facenum = facenum + 1 client.publish(topic + str(facenum), str(midFaceX) + "," + str(midFaceY), 0) print topic + str(facenum), str(midFaceX) + "," + str(midFaceY) cv.ShowImage("result", img)
def draw_common(points): success, center, radius = cv.MinEnclosingCircle(points) if success: cv.Circle(img, roundxy(center), cv.Round(radius), cv.CV_RGB(255, 255, 0), 1, cv.CV_AA, 0) box = cv.MinAreaRect2(points) box_vtx = [roundxy(p) for p in cv.BoxPoints(box)] cv.PolyLine(img, [box_vtx], 1, cv.CV_RGB(0, 255, 255), 1, cv.CV_AA)
def detect_and_draw(img, cascade, mask): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if (cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t print "detection time = %gms" % (t / (cv.GetTickFrequency() * 1000.)) if faces: for ((x, y, w, h), n) in faces: # Affichage du carré de recherche xmoustache = int((x * image_scale) + w * 0.5) ymoustache = int((y * image_scale) + h * 1.25) wmoustache = int(w * 0.5 * image_scale) hmoustache = int(h * 0.19 * image_scale) img_mask = cv.CreateImage((wmoustache, hmoustache), mask.depth, mask.nChannels) cv.SetImageROI( img, (xmoustache, ymoustache, wmoustache, hmoustache)) cv.Resize(mask, img_mask, cv.CV_INTER_LINEAR) # Affichage du carré de recherche cv.Sub(img, img_mask, img) cv.ResetImageROI(img) pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) #cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) cv.ShowImage("result", img)
def detect_and_draw(img,cascade): gray=cv.CreateImage((img.width,img.height),8,1) small_img=cv.CreateImage((cv.Round(img.width/image_scale),cv.Round(img.height/image_scale)),8,1) cv.CvtColor(img,gray,cv.CV_BGR2GRAY) cv.Resize(gray,small_img,cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img,small_img) if(cascade): t=cv.GetTickCount() faces=cv.HaarDetectObjects(small_img,cascade,cv.CreateMemStorage(0),haar_scale,min_neighbors,haar_flags,min_size) t=cv.GetTickCount()-t print "time taken for detection = %gms"%(t/(cv.GetTickFrequency()*1000.)) if faces: for ((x,y,w,h),n) in faces: pt1=(int(x*image_scale),int(y*image_scale)) pt2=(int((x+w)*image_scale),int((y+h)*image_scale)) cv.Rectangle(img,pt1,pt2,cv.RGB(255,0,0),3,8,0) cv.ShowImage("video",img)
def detect_and_draw(img, cascade): gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) midFace = None if (cascade): t = cv.GetTickCount() # HaarDetectObjects takes 0.02s faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t if faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) # get the xy corner co-ords, calc the midFace location x1 = pt1[0] x2 = pt2[0] y1 = pt1[1] y2 = pt2[1] midFaceX = x1 + ((x2 - x1) / 2) midFaceY = y1 + ((y2 - y1) / 2) midFace = (midFaceX, midFaceY) cv.ShowImage("result", img) return midFace