def read(self): frame=self.input.read() if self.enabled: cv_rs = [None]*4 cv_thresh = [0]*4 cv_max = [255]*4 for i in self.channels : cv_rs[i] = cv.cvCreateImage(cv.cvSize(frame.width,frame.height),frame.depth,1) cv_thresh[i] = self.thresholds[i] cv_max[i] = self.max_thresholds[i] # extract the color channel cv.cvSplit(frame,cv_rs[0],cv_rs[1],cv_rs[2],cv_rs[3]) #self.debug_print(cv_rs) for i in self.channels : cv.cvThreshold(cv_rs[i],cv_rs[i],cv_thresh[i],cv_max[i],self.type) #cv_thresh = cv.cvCreateImage(cv.cvSize(frame.width,frame.height),frame.depth,3) cv.cvZero(frame) cv.cvMerge(cv_rs[0],cv_rs[1],cv_rs[2],cv_rs[3],frame) #frame = cv_thresh return frame
def __findContour(self, filename): #find the contour of images, and save all points in self.vKeyPoints self.img = highgui.cvLoadImage (filename) self.grayimg = cv.cvCreateImage(cv.cvSize(self.img.width, self.img.height), 8,1) self.drawimg = cv.cvCreateImage(cv.cvSize(self.img.width, self.img.height), 8,3) cv.cvCvtColor (self.img, self.grayimg, cv.CV_BGR2GRAY) cv.cvSmooth(self.grayimg, self.grayimg, cv.CV_BLUR, 9) cv.cvSmooth(self.grayimg, self.grayimg, cv.CV_BLUR, 9) cv.cvSmooth(self.grayimg, self.grayimg, cv.CV_BLUR, 9) cv.cvThreshold( self.grayimg, self.grayimg, self.threshold, self.threshold +100, cv.CV_THRESH_BINARY ) cv.cvZero(self.drawimg) storage = cv.cvCreateMemStorage(0) nb_contours, cont = cv.cvFindContours (self.grayimg, storage, cv.sizeof_CvContour, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_NONE, cv.cvPoint (0,0)) cv.cvDrawContours (self.drawimg, cont, cv.cvScalar(255,255,255,0), cv.cvScalar(255,255,255,0), 1, 1, cv.CV_AA, cv.cvPoint (0, 0)) self.allcurve = [] idx = 0 for c in cont.hrange(): PointArray = cv.cvCreateMat(1, c.total , cv.CV_32SC2) PointArray2D32f= cv.cvCreateMat( 1, c.total , cv.CV_32FC2) cv.cvCvtSeqToArray(c, PointArray, cv.cvSlice(0, cv.CV_WHOLE_SEQ_END_INDEX)) fpoints = [] for i in range(c.total): kp = myPoint() kp.x = cv.cvGet2D(PointArray,0, i)[0] kp.y = cv.cvGet2D(PointArray,0, i)[1] kp.index = idx idx += 1 fpoints.append(kp) self.allcurve.append(fpoints) self.curvelength = idx
def preproc(image): from opencv.cv import cvCreateMat, cvThreshold, CV_THRESH_OTSU rows = image.rows cols = image.cols typ = image.type binary_image = cvCreateMat(rows, cols, typ) cvThreshold(image, binary_image, 128, 255, CV_THRESH_OTSU) return binary_image
def preproc(image): from opencv.cv import cvCreateMat,cvThreshold,CV_THRESH_OTSU rows = image.rows cols = image.cols typ = image.type binary_image = cvCreateMat(rows,cols,typ) cvThreshold(image, binary_image,128,255, CV_THRESH_OTSU) return binary_image
def _get_threshold_frame(self,frame=None,thresh=None,max_thresh=255,type=cv.CV_THRESH_BINARY) : if frame is None : frame = self._get_grayscale_frame() if thresh is None : thresh = self.color_thresh # threshold the image for > self.color_thresh value cv_thresh = cv.cvCreateImage(cv.cvSize(frame.width,frame.height),frame.depth,1) cv.cvThreshold(frame,cv_thresh,thresh,max_thresh,type) return cv_thresh
def run(self): if self.capture: webcam_frame = highgui.cvQueryFrame( self.capture ) else: print "Capture failed!" return if self.inverted_video.get_active(): highgui.cvConvertImage(webcam_frame, webcam_frame, highgui.CV_CVTIMG_FLIP) highgui.cvConvertImage(webcam_frame, self.display_frame, highgui.CV_CVTIMG_SWAP_RB) if False: # PROCESS WEBCAM FRAME HERE... inputImage = cv.cvCreateImage(cv.cvGetSize(webcam_frame), cv.IPL_DEPTH_8U, 1) cv.cvCvtColor(webcam_frame, inputImage, cv.CV_RGB2GRAY); cv.cvThreshold(inputImage, inputImage, 128, 255, cv.CV_THRESH_BINARY) mysize = cv.cvGetSize(webcam_frame) height = mysize.height width = mysize.width # Find horizontal first-moment: if False: mysum = 0 for i in range(height): mysum += sum(inputImage[i,:]) print "Sum:", mysum cv.cvMerge( inputImage, inputImage, inputImage, None, self.display_frame ) incoming_pixbuf = gtk.gdk.pixbuf_new_from_data( self.display_frame.imageData, gtk.gdk.COLORSPACE_RGB, False, 8, self.display_frame.width, self.display_frame.height, self.display_frame.widthStep) incoming_pixbuf.copy_area(0, 0, self.display_frame.width, self.display_frame.height, self.webcam_pixbuf, 0, 0) self.video_image.queue_draw() return self.video_enabled_button.get_active()
def read(self) : frame=self.input.read() if self.debug : raw_frame = cv.cvCreateImage(cv.cvSize(frame.width,frame.height),frame.depth,frame.nChannels) cv.cvCopy(frame,raw_frame,None) self.raw_frame_surface=pygame.image.frombuffer(frame.imageData,(frame.width,frame.height),'RGB') if self.enabled : cv_rs = cv.cvCreateImage(cv.cvSize(frame.width,frame.height),frame.depth,1) # convert color cv.cvCvtColor(frame,cv_rs,cv.CV_BGR2GRAY) # invert the image cv.cvSubRS(cv_rs, 255, cv_rs, None); # threshold the image frame = cv.cvCreateImage(cv.cvSize(frame.width,frame.height),frame.depth,1) cv.cvThreshold(cv_rs, frame, self.threshold, 255, cv.CV_THRESH_BINARY) if self.debug : thresh_frame = cv.cvCreateImage(cv.cvSize(frame.width,frame.height),frame.depth,3) cv.cvCvtColor(frame,thresh_frame,cv.CV_GRAY2RGB) self.thresh_frame_surface=pygame.image.frombuffer(thresh_frame.imageData,(frame.width,frame.height),'RGB') # I think these functions are too specialized for transforms cv.cvSmooth(frame,frame,cv.CV_GAUSSIAN,3, 0, 0, 0 ) cv.cvErode(frame, frame, None, 1) cv.cvDilate(frame, frame, None, 1) num_contours,contours=cv.cvFindContours(frame,self.storage,cv.sizeof_CvContour,cv.CV_RETR_LIST,cv.CV_CHAIN_APPROX_NONE,cv.cvPoint(0,0)) if contours is None : return [] else : contours = cv.cvApproxPoly( contours, cv.sizeof_CvContour, self.storage, cv.CV_POLY_APPROX_DP, 3, 1 ); if contours is None : return [] else : final_contours = [] for c in contours.hrange() : area = abs(cv.cvContourArea(c)) #self.debug_print('Polygon Area: %f'%area) if area >= self.min_area : lst = [] for pt in c : lst.append((pt.x,pt.y)) final_contours.append(lst) contours = contours.h_next return final_contours return []
def get_thresholded(self,gray_source,threshold): #Allocate a new image threshed=cv.cvCreateImage(cv.cvGetSize(gray_source),gray_source.depth,1) #Subtract 255 from all values in the image? cv.cvSubRS(gray_source,cv.cvRealScalar(255),threshed,None) #Apply a binary threshold to the image cv.cvThreshold(gray_source,threshed,threshold,255,cv.CV_THRESH_BINARY) #Release the source image cv.cvReleaseImage(gray_source) return threshed
def run(self): if self.capture: webcam_frame = highgui.cvQueryFrame(self.capture) else: print "Capture failed!" return if self.inverted_video.get_active(): highgui.cvConvertImage(webcam_frame, webcam_frame, highgui.CV_CVTIMG_FLIP) highgui.cvConvertImage(webcam_frame, self.display_frame, highgui.CV_CVTIMG_SWAP_RB) if False: # PROCESS WEBCAM FRAME HERE... inputImage = cv.cvCreateImage(cv.cvGetSize(webcam_frame), cv.IPL_DEPTH_8U, 1) cv.cvCvtColor(webcam_frame, inputImage, cv.CV_RGB2GRAY) cv.cvThreshold(inputImage, inputImage, 128, 255, cv.CV_THRESH_BINARY) mysize = cv.cvGetSize(webcam_frame) height = mysize.height width = mysize.width # Find horizontal first-moment: if False: mysum = 0 for i in range(height): mysum += sum(inputImage[i, :]) print "Sum:", mysum cv.cvMerge(inputImage, inputImage, inputImage, None, self.display_frame) incoming_pixbuf = gtk.gdk.pixbuf_new_from_data( self.display_frame.imageData, gtk.gdk.COLORSPACE_RGB, False, 8, self.display_frame.width, self.display_frame.height, self.display_frame.widthStep) incoming_pixbuf.copy_area(0, 0, self.display_frame.width, self.display_frame.height, self.webcam_pixbuf, 0, 0) self.video_image.queue_draw() return self.video_enabled_button.get_active()
def __findedge(self, filename): tmpimg = highgui.cvLoadImage (filename) self.img = cv.cvCreateImage(cv.cvSize(int(tmpimg.width * self.enlarge), int(tmpimg.height * self.enlarge)), 8, 3) cv.cvResize(tmpimg, self.img, cv.CV_INTER_LINEAR) if (self.drawimage): self.drawimg = cv.cvCloneImage(self.img) else: self.drawimg = cv.cvCreateImage(cv.cvGetSize(self.img), 8, 3) greyimg = cv.cvCreateImage(cv.cvSize(self.img.width, self.img.height), 8,1) cv.cvCvtColor(self.img, greyimg, cv.CV_BGR2GRAY) self.allcurve = [] for i in range(80, 200, 20): bimg = cv.cvCloneImage(greyimg) cv.cvSmooth(bimg, bimg, cv.CV_MEDIAN, 9) # cv.cvSmooth(bimg, bimg, cv.CV_BILATERAL, 9) # cv.cvSmooth(bimg, bimg, cv.CV_BLUR, 9) # cv.cvSmooth(bimg, bimg, cv.CV_BLUR, 9) cv.cvThreshold(greyimg, bimg, i, 255, cv.CV_THRESH_BINARY) self.__findcurve(bimg)
def threshold_image(image, n=[]): """Record the first 5 images to get a background, then diff current frame with the last saved frame. """ if len(n) < 5: # n[4] will be our background # First capture a few images n.append(cv.cvCloneMat(image)) if len(n) == 5: # last time here # could do averaging here. pass return image original = n[4] differenceImage = cv.cvCloneMat(image) cv.cvAbsDiff(image, original, differenceImage) """The threshold value determines the amount of "Change" required before something will show up""" thresholdValue = 50 # 32 cv.cvThreshold(differenceImage, differenceImage, thresholdValue, 255, cv.CV_THRESH_BINARY) # Convert to one channel gray = cv.cvCreateImage(cv.cvGetSize(differenceImage), 8, 1) cv.cvCvtColor(differenceImage, gray, cv.CV_BGR2GRAY) # Use median filter to remove salt and pepper noise. cv.cvSmooth(gray, gray, cv.CV_MEDIAN, 15) # Dilate and the threshold image # It adds a border to the object. #cv.cvDilate(gray,gray, None, 9) # Add a bit of Blur to the threshold mask cv.cvSmooth(gray, gray, cv.CV_GAUSSIAN, 5) result = cv.cvCloneMat(image) cv.cvSetZero(result) cv.cvAnd(image, image, result, gray) return result
def threshold_image(image, n=[]): """Record the first 5 images to get a background, then diff current frame with the last saved frame. """ if len(n) < 5: # n[4] will be our background # First capture a few images n.append(cv.cvCloneMat(image)) if len(n) == 5: # last time here # could do averaging here. pass return image original = n[4] differenceImage = cv.cvCloneMat( image ) cv.cvAbsDiff( image, original, differenceImage ) """The threshold value determines the amount of "Change" required before something will show up""" thresholdValue = 50 # 32 cv.cvThreshold( differenceImage, differenceImage, thresholdValue, 255, cv.CV_THRESH_BINARY ) # Convert to one channel gray = cv.cvCreateImage( cv.cvGetSize(differenceImage), 8, 1 ) cv.cvCvtColor( differenceImage, gray, cv.CV_BGR2GRAY ) # Use median filter to remove salt and pepper noise. cv.cvSmooth(gray, gray, cv.CV_MEDIAN, 15) # Dilate and the threshold image # It adds a border to the object. #cv.cvDilate(gray,gray, None, 9) # Add a bit of Blur to the threshold mask cv.cvSmooth(gray, gray, cv.CV_GAUSSIAN, 5) result = cv.cvCloneMat( image) cv.cvSetZero(result) cv.cvAnd(image,image, result, gray) return result
def __findedge(self, filename): tmpimg = highgui.cvLoadImage(filename) self.img = cv.cvCreateImage( cv.cvSize(int(tmpimg.width * self.enlarge), int(tmpimg.height * self.enlarge)), 8, 3) cv.cvResize(tmpimg, self.img, cv.CV_INTER_LINEAR) if (self.drawimage): self.drawimg = cv.cvCloneImage(self.img) else: self.drawimg = cv.cvCreateImage(cv.cvGetSize(self.img), 8, 3) greyimg = cv.cvCreateImage(cv.cvSize(self.img.width, self.img.height), 8, 1) cv.cvCvtColor(self.img, greyimg, cv.CV_BGR2GRAY) self.allcurve = [] for i in range(80, 200, 20): bimg = cv.cvCloneImage(greyimg) cv.cvSmooth(bimg, bimg, cv.CV_MEDIAN, 9) # cv.cvSmooth(bimg, bimg, cv.CV_BILATERAL, 9) # cv.cvSmooth(bimg, bimg, cv.CV_BLUR, 9) # cv.cvSmooth(bimg, bimg, cv.CV_BLUR, 9) cv.cvThreshold(greyimg, bimg, i, 255, cv.CV_THRESH_BINARY) self.__findcurve(bimg)
blob_overlay = False while True: # 1. capture the current image frame = highgui.cvQueryFrame(capture) if frame is None: # no image captured... end the processing break # mirror the captured image cv.cvFlip(frame, None, 1) cv.cvCvtColor(frame, my_grayscale, cv.CV_RGB2GRAY) cv.cvThreshold(my_grayscale, my_grayscale, 128, 255, cv.CV_THRESH_BINARY) if not blob_overlay: # Convert black-and-white version back into three-color representation cv.cvCvtColor(my_grayscale, frame, cv.CV_GRAY2RGB) myblobs = CBlobResult(my_grayscale, mask, 100, True) myblobs.filter_blobs(10, 10000) blob_count = myblobs.GetNumBlobs() for i in range(blob_count): my_enumerated_blob = myblobs.GetBlob(i) # print "%d: Area = %d" % (i, my_enumerated_blob.Area()) my_enumerated_blob.FillBlob(frame, hsv2rgb(i * 180.0 / blob_count), 0, 0)
def detect_squares(self, img_grey, img_orig): """ Find squares within the video stream and draw them """ cv.cvClearMemStorage(self.faces_storage) N = 11 thresh = 5 sz = cv.cvSize(img_grey.width & -2, img_grey.height & -2) timg = cv.cvCloneImage(img_orig) pyr = cv.cvCreateImage(cv.cvSize(sz.width/2, sz.height/2), 8, 3) # create empty sequence that will contain points - # 4 points per square (the square's vertices) squares = cv.cvCreateSeq(0, cv.sizeof_CvSeq, cv.sizeof_CvPoint, self.squares_storage) squares = cv.CvSeq_CvPoint.cast(squares) # select the maximum ROI in the image # with the width and height divisible by 2 subimage = cv.cvGetSubRect(timg, cv.cvRect(0, 0, sz.width, sz.height)) cv.cvReleaseImage(timg) # down-scale and upscale the image to filter out the noise cv.cvPyrDown(subimage, pyr, 7) cv.cvPyrUp(pyr, subimage, 7) cv.cvReleaseImage(pyr) tgrey = cv.cvCreateImage(sz, 8, 1) # find squares in every color plane of the image for c in range(3): # extract the c-th color plane channels = [None, None, None] channels[c] = tgrey cv.cvSplit(subimage, channels[0], channels[1], channels[2], None) for l in range(N): # hack: use Canny instead of zero threshold level. # Canny helps to catch squares with gradient shading if(l == 0): # apply Canny. Take the upper threshold from slider # and set the lower to 0 (which forces edges merging) cv.cvCanny(tgrey, img_grey, 0, thresh, 5) # dilate canny output to remove potential # holes between edge segments cv.cvDilate(img_grey, img_grey, None, 1) else: # apply threshold if l!=0: # tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 cv.cvThreshold(tgrey, img_grey, (l+1)*255/N, 255, cv.CV_THRESH_BINARY) # find contours and store them all as a list count, contours = cv.cvFindContours(img_grey, self.squares_storage, cv.sizeof_CvContour, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_SIMPLE, cv.cvPoint(0,0)) if not contours: continue # test each contour for contour in contours.hrange(): # approximate contour with accuracy proportional # to the contour perimeter result = cv.cvApproxPoly(contour, cv.sizeof_CvContour, self.squares_storage, cv.CV_POLY_APPROX_DP, cv.cvContourPerimeter(contours)*0.02, 0) # square contours should have 4 vertices after approximation # relatively large area (to filter out noisy contours) # and be convex. # Note: absolute value of an area is used because # area may be positive or negative - in accordance with the # contour orientation if(result.total == 4 and abs(cv.cvContourArea(result)) > 1000 and cv.cvCheckContourConvexity(result)): s = 0 for i in range(5): # find minimum angle between joint # edges (maximum of cosine) if(i >= 2): t = abs(self.squares_angle(result[i], result[i-2], result[i-1])) if s<t: s = t # if cosines of all angles are small # (all angles are ~90 degree) then write quandrange # vertices to resultant sequence if(s < 0.3): for i in range(4): squares.append(result[i]) cv.cvReleaseImage(tgrey) return squares
# niveau de gris cv.cvSub(frameGray, frameGrayBg, framewithoutbg) # soustraction du background cv.cvMul(framewithoutbg, framewithoutbg, framemul, get_gain()) # amplification cv.cvSmooth(framemul, framelisser1, cv.CV_BLUR, param_liss[0], param2_liss[0]) # lissage if first == 0: # "moyenne" sur deux image cv.cvAnd(framelisser1, framelisser2, framelisser) if first == 1: framelisser = cv.cvCloneImage(framelisser1) framelisser2 = cv.cvCloneImage(framelisser1) cv.cvThreshold(framelisser, frameBin, get_seuil(), float(255), cv.CV_THRESH_BINARY) # binaristaion de l image ################ run detection ################ zone_active = zoneActivePremier(zone_active, frameBin) if len(zone_active) == 0: centrePointeur = [] info_size = [] if len(zone_active) != 0: for i in range(1, nb_div_zone[0] + 1): zone_active = zoneActive(zone_active, frameBin, i) pointeur = pointeurPrecision(zone_active, frameBin) pointeur = FiltreRedondance( pointeur[0], pointeur[1] ) # pointeur[0] : centrePointeur , pointeur[1] : info_size centrePointeur = pointeur[0]
def detect_squares(self, img): """ Find squares within the video stream and draw them """ N = 11 thresh = 5 sz = cv.cvSize(img.width & -2, img.height & -2) timg = cv.cvCloneImage(img) gray = cv.cvCreateImage(sz, 8, 1) pyr = cv.cvCreateImage(cv.cvSize(sz.width / 2, sz.height / 2), 8, 3) # create empty sequence that will contain points - # 4 points per square (the square's vertices) squares = cv.cvCreateSeq(0, cv.sizeof_CvSeq, cv.sizeof_CvPoint, self.storage) squares = cv.CvSeq_CvPoint.cast(squares) # select the maximum ROI in the image # with the width and height divisible by 2 subimage = cv.cvGetSubRect(timg, cv.cvRect(0, 0, sz.width, sz.height)) # down-scale and upscale the image to filter out the noise cv.cvPyrDown(subimage, pyr, 7) cv.cvPyrUp(pyr, subimage, 7) tgray = cv.cvCreateImage(sz, 8, 1) # find squares in every color plane of the image for c in range(3): # extract the c-th color plane channels = [None, None, None] channels[c] = tgray cv.cvSplit(subimage, channels[0], channels[1], channels[2], None) for l in range(N): # hack: use Canny instead of zero threshold level. # Canny helps to catch squares with gradient shading if (l == 0): # apply Canny. Take the upper threshold from slider # and set the lower to 0 (which forces edges merging) cv.cvCanny(tgray, gray, 0, thresh, 5) # dilate canny output to remove potential # holes between edge segments cv.cvDilate(gray, gray, None, 1) else: # apply threshold if l!=0: # tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 cv.cvThreshold(tgray, gray, (l + 1) * 255 / N, 255, cv.CV_THRESH_BINARY) # find contours and store them all as a list count, contours = cv.cvFindContours(gray, self.storage, cv.sizeof_CvContour, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_SIMPLE, cv.cvPoint(0, 0)) if not contours: continue # test each contour for contour in contours.hrange(): # approximate contour with accuracy proportional # to the contour perimeter result = cv.cvApproxPoly( contour, cv.sizeof_CvContour, self.storage, cv.CV_POLY_APPROX_DP, cv.cvContourPerimeter(contours) * 0.02, 0) # square contours should have 4 vertices after approximation # relatively large area (to filter out noisy contours) # and be convex. # Note: absolute value of an area is used because # area may be positive or negative - in accordance with the # contour orientation if (result.total == 4 and abs(cv.cvContourArea(result)) > 1000 and cv.cvCheckContourConvexity(result)): s = 0 for i in range(5): # find minimum angle between joint # edges (maximum of cosine) if (i >= 2): t = abs( self.squares_angle(result[i], result[i - 2], result[i - 1])) if s < t: s = t # if cosines of all angles are small # (all angles are ~90 degree) then write quandrange # vertices to resultant sequence if (s < 0.3): for i in range(4): squares.append(result[i]) i = 0 while i < squares.total: pt = [] # read 4 vertices pt.append(squares[i]) pt.append(squares[i + 1]) pt.append(squares[i + 2]) pt.append(squares[i + 3]) # draw the square as a closed polyline cv.cvPolyLine(img, [pt], 1, cv.CV_RGB(0, 255, 0), 3, cv.CV_AA, 0) i += 4 return img
def process_image(slider_pos): """ Define trackbar callback functon. This function find contours, draw it and approximate it by ellipses. """ stor = cv.cvCreateMemStorage(0) # Threshold the source image. This needful for cv.cvFindContours(). cv.cvThreshold(image03, image02, slider_pos, 255, cv.CV_THRESH_BINARY) # Find all contours. nb_contours, cont = cv.cvFindContours(image02, stor, cv.sizeof_CvContour, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_NONE, cv.cvPoint(0, 0)) # Clear images. IPL use. cv.cvZero(image02) cv.cvZero(image04) # This cycle draw all contours and approximate it by ellipses. for c in cont.hrange(): count = c.total # This is number point in contour # Number point must be more than or equal to 6 (for cv.cvFitEllipse_32f). if (count < 6): continue # Alloc memory for contour point set. PointArray = cv.cvCreateMat(1, count, cv.CV_32SC2) PointArray2D32f = cv.cvCreateMat(1, count, cv.CV_32FC2) # Get contour point set. cv.cvCvtSeqToArray(c, PointArray, cv.cvSlice(0, cv.CV_WHOLE_SEQ_END_INDEX)) # Convert CvPoint set to CvBox2D32f set. cv.cvConvert(PointArray, PointArray2D32f) box = cv.CvBox2D() # Fits ellipse to current contour. box = cv.cvFitEllipse2(PointArray2D32f) # Draw current contour. cv.cvDrawContours(image04, c, cv.CV_RGB(255, 255, 255), cv.CV_RGB(255, 255, 255), 0, 1, 8, cv.cvPoint(0, 0)) # Convert ellipse data from float to integer representation. center = cv.CvPoint() size = cv.CvSize() center.x = cv.cvRound(box.center.x) center.y = cv.cvRound(box.center.y) size.width = cv.cvRound(box.size.width * 0.5) size.height = cv.cvRound(box.size.height * 0.5) box.angle = -box.angle # Draw ellipse. cv.cvEllipse(image04, center, size, box.angle, 0, 360, cv.CV_RGB(0, 0, 255), 1, cv.CV_AA, 0) # Show image. HighGUI use. highgui.cvShowImage("Result", image04)
def compute_saliency(image): global thresh global scale saliency_scale = int(math.pow(2,scale)); bw_im1 = cv.cvCreateImage(cv.cvGetSize(image), cv.IPL_DEPTH_8U,1) cv.cvCvtColor(image, bw_im1, cv.CV_BGR2GRAY) bw_im = cv.cvCreateImage(cv.cvSize(saliency_scale,saliency_scale), cv.IPL_DEPTH_8U,1) cv.cvResize(bw_im1, bw_im) highgui.cvShowImage("BW", bw_im) realInput = cv.cvCreateImage( cv.cvGetSize(bw_im), cv.IPL_DEPTH_32F, 1); imaginaryInput = cv.cvCreateImage( cv.cvGetSize(bw_im), cv.IPL_DEPTH_32F, 1); complexInput = cv.cvCreateImage( cv.cvGetSize(bw_im), cv.IPL_DEPTH_32F, 2); cv.cvScale(bw_im, realInput, 1.0, 0.0); cv.cvZero(imaginaryInput); cv.cvMerge(realInput, imaginaryInput, None, None, complexInput); dft_M = saliency_scale #cv.cvGetOptimalDFTSize( bw_im.height - 1 ); dft_N = saliency_scale #cv.cvGetOptimalDFTSize( bw_im.width - 1 ); dft_A = cv.cvCreateMat( dft_M, dft_N, cv.CV_32FC2 ); image_Re = cv.cvCreateImage( cv.cvSize(dft_N, dft_M), cv.IPL_DEPTH_32F, 1); image_Im = cv.cvCreateImage( cv.cvSize(dft_N, dft_M), cv.IPL_DEPTH_32F, 1); # copy A to dft_A and pad dft_A with zeros tmp = cv.cvGetSubRect( dft_A, cv.cvRect(0,0, bw_im.width, bw_im.height)); cv.cvCopy( complexInput, tmp, None ); if(dft_A.width > bw_im.width): tmp = cv.cvGetSubRect( dft_A, cv.cvRect(bw_im.width,0, dft_N - bw_im.width, bw_im.height)); cv.cvZero( tmp ); cv.cvDFT( dft_A, dft_A, cv.CV_DXT_FORWARD, complexInput.height ); cv.cvSplit( dft_A, image_Re, image_Im, None, None ); # Compute the phase angle image_Mag = cv.cvCreateImage(cv.cvSize(dft_N, dft_M), cv.IPL_DEPTH_32F, 1); image_Phase = cv.cvCreateImage(cv.cvSize(dft_N, dft_M), cv.IPL_DEPTH_32F, 1); #compute the phase of the spectrum cv.cvCartToPolar(image_Re, image_Im, image_Mag, image_Phase, 0) log_mag = cv.cvCreateImage(cv.cvSize(dft_N, dft_M), cv.IPL_DEPTH_32F, 1); cv.cvLog(image_Mag, log_mag) #Box filter the magnitude, then take the difference image_Mag_Filt = cv.cvCreateImage(cv.cvSize(dft_N, dft_M), cv.IPL_DEPTH_32F, 1); filt = cv.cvCreateMat(3,3, cv.CV_32FC1); cv.cvSet(filt,cv.cvScalarAll(-1.0/9.0)) cv.cvFilter2D(log_mag, image_Mag_Filt, filt, cv.cvPoint(-1,-1)) cv.cvAdd(log_mag, image_Mag_Filt, log_mag, None) cv.cvExp(log_mag, log_mag) cv.cvPolarToCart(log_mag, image_Phase, image_Re, image_Im,0); cv.cvMerge(image_Re, image_Im, None, None, dft_A) cv.cvDFT( dft_A, dft_A, cv.CV_DXT_INVERSE, complexInput.height) tmp = cv.cvGetSubRect( dft_A, cv.cvRect(0,0, bw_im.width, bw_im.height)); cv.cvCopy( tmp, complexInput, None ); cv.cvSplit(complexInput, realInput, imaginaryInput, None, None) min, max = cv.cvMinMaxLoc(realInput); #cv.cvScale(realInput, realInput, 1.0/(max-min), 1.0*(-min)/(max-min)); cv.cvSmooth(realInput, realInput); threshold = thresh/100.0*cv.cvAvg(realInput)[0] cv.cvThreshold(realInput, realInput, threshold, 1.0, cv.CV_THRESH_BINARY) tmp_img = cv.cvCreateImage(cv.cvGetSize(bw_im1),cv.IPL_DEPTH_32F, 1) cv.cvResize(realInput,tmp_img) cv.cvScale(tmp_img, bw_im1, 255,0) return bw_im1
limiar = (0.01, 0.001, 0.21, 0.18) target = [] target_mod = [] target_c = [] # Armazenamento temporario # Temporary storage storage1 = cv.cvCreateMemStorage() storage2 = cv.cvCreateMemStorage() # Carrega, binariza e procura o contorno dos padroes # Load, binarize and find contours for i in range(0,len(padroes)): target.append(hg.cvLoadImage(padroes[i], hg.CV_LOAD_IMAGE_GRAYSCALE)) target_mod.append(cv.cvCreateImage((target[i].width,target[i].height), cv.IPL_DEPTH_8U, 1)) cv.cvThreshold(target[i],target_mod[i],200,254,cv.CV_THRESH_BINARY) target_c.append(cv.cvFindContours(target_mod[i], storage1)[1]) target_c[i] = cv.cvApproxPoly(target_c[i],cv.sizeof_CvContour,storage1,cv.CV_POLY_APPROX_DP,1) frame_mod = cv.cvCreateImage((hg.cvGetCaptureProperty(capture,hg.CV_CAP_PROP_FRAME_WIDTH), hg.cvGetCaptureProperty(capture,hg.CV_CAP_PROP_FRAME_HEIGHT)), cv.IPL_DEPTH_8U, 1) hg.cvNamedWindow("Resultado") hg.cvNamedWindow("Binarizado") #strut = cv.cvCreateStructuringElementEx(3,3,0,0,cv.CV_SHAPE_CROSS) while True: turn = -1 # Captura o frame, binariza, procura por contornos e checa com os padroes # Capture frame, binarize, find contours and check with known patterns frame = hg.cvQueryFrame(capture) cv.cvCvtColor(frame, frame_mod,cv.CV_RGB2GRAY)
def SetBinary(self, t): self.drawimg = cv.cvCreateImage(cv.cvGetSize(self.img), 8, 3) cv.cvThreshold(self.img, self.drawimg, t, 255, cv.CV_THRESH_BINARY)
def process_image( slider_pos ): """ Define trackbar callback functon. This function find contours, draw it and approximate it by ellipses. """ stor = cv.cvCreateMemStorage(0); # Threshold the source image. This needful for cv.cvFindContours(). cv.cvThreshold( image03, image02, slider_pos, 255, cv.CV_THRESH_BINARY ); # Find all contours. nb_contours, cont = cv.cvFindContours (image02, stor, cv.sizeof_CvContour, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_NONE, cv.cvPoint (0,0)) # Clear images. IPL use. cv.cvZero(image02); cv.cvZero(image04); # This cycle draw all contours and approximate it by ellipses. for c in cont.hrange(): count = c.total; # This is number point in contour # Number point must be more than or equal to 6 (for cv.cvFitEllipse_32f). if( count < 6 ): continue; # Alloc memory for contour point set. PointArray = cv.cvCreateMat(1, count, cv.CV_32SC2) PointArray2D32f= cv.cvCreateMat( 1, count, cv.CV_32FC2) # Get contour point set. cv.cvCvtSeqToArray(c, PointArray, cv.cvSlice(0, cv.CV_WHOLE_SEQ_END_INDEX)); # Convert CvPoint set to CvBox2D32f set. cv.cvConvert( PointArray, PointArray2D32f ) box = cv.CvBox2D() # Fits ellipse to current contour. box = cv.cvFitEllipse2(PointArray2D32f); # Draw current contour. cv.cvDrawContours(image04, c, cv.CV_RGB(255,255,255), cv.CV_RGB(255,255,255),0,1,8,cv.cvPoint(0,0)); # Convert ellipse data from float to integer representation. center = cv.CvPoint() size = cv.CvSize() center.x = cv.cvRound(box.center.x); center.y = cv.cvRound(box.center.y); size.width = cv.cvRound(box.size.width*0.5); size.height = cv.cvRound(box.size.height*0.5); box.angle = -box.angle; # Draw ellipse. cv.cvEllipse(image04, center, size, box.angle, 0, 360, cv.CV_RGB(0,0,255), 1, cv.CV_AA, 0); # Show image. HighGUI use. highgui.cvShowImage( "Result", image04 );