def main(): """ Just the test This method is a good resource on how to handle the results. Save images in this method if you have to. """ filename = sys.argv[1] image = highgui.cvLoadImage (filename) cutRatios = [lib.PHI] #cutRatios = [0.618] settings = Settings(cutRatios) image = highgui.cvLoadImage (filename) thickness = 4 settings.setMarginPercentage(0.025) settings.setMethod(sys.argv[3]) cut = int(sys.argv[2]) winname = sys.argv[1] #settings.setThresholds(100,150) # Set the color for the boxes #color = lib.COL_BLACK #color = lib.COL_WHITE #color = lib.COL_RED color = lib.COL_GREEN #color = lib.COL_BLUE blobImg = blobResult(image, settings, cut) boxxImg = boundingBoxResult(image, settings, cut, thickness, color) cutt = lib.findMeans(cv.cvGetSize(image), settings.cutRatios[0])[cut] # cuttet verdi, dog skal det vi generaliseres lidt oriantesen = cutt.getPoints()[0].x == cutt.getPoints()[1].x if oriantesen: cutPixel = cutt.getPoints()[1].x else: cutPixel = cutt.getPoints()[1].y if oriantesen: # print 'hej' cv.cvLine(boxxImg, cv.cvPoint(cutPixel, cutt.getPoints()[0].y), cv.cvPoint(cutPixel, cutt.getPoints()[1].y), lib.COL_RED) else: cv.cvLine(boxxImg, cv.cvPoint(cutt.getPoints()[0].x, cutPixel), cv.cvPoint(cutt.getPoints()[1].x, cutPixel), lib.COL_RED) # Save images highgui.cvSaveImage('flood_cut_%s.png' % cut, boxxImg) highgui.cvSaveImage('blobs_cut_%s.png' % cut, blobImg) # Show images compareImages(blobImg, boxxImg, "blob", winname)
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 face_detect(file, closeafter=True): """Converts an image to grayscale and prints the locations of any faces found""" if hasattr(file, 'read'): _, filename = tempfile.mkstemp() tmphandle = open(filename, 'w') shutil.copyfileobj(file, tmphandle) tmphandle.close() if closeafter: file.close() deleteafter = True else: filename = file deleteafter = False image = cvLoadImage(filename) grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1) cvCvtColor(image, grayscale, CV_BGR2GRAY) storage = cvCreateMemStorage(0) cvClearMemStorage(storage) cvEqualizeHist(grayscale, grayscale) cascade = cvLoadHaarClassifierCascade( '/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml', cvSize(1,1)) faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(50,50)) if deleteafter: os.unlink(filename) return (image.width, image.height), faces
def prepare(self): log.info('prepare(): trainpath: %s, symbolpath: %s' % colorize( (self.trainpath, self.symbolpath))) trainfile = open(self.trainpath, 'w') filter = re.compile(SYMBOL_FILTER) symbols = [] for name in os.listdir(self.symbolpath): if filter.match(name): symbols.append(name) trainfile.write('%d %d %d\n' % (len(symbols), self.input, self.output)) for name in symbols: img = cvLoadImage(SYMBOLS_PATH + self.site + '/' + name, CV_LOAD_IMAGE_GRAYSCALE) data = self.getdata(img) trainfile.write('%s\n' % ' '.join(map(str, data))) c = name[0] n = self.charset.index(c) trainfile.write('-1 ' * n + '1' + ' -1' * (self.output - n - 1) + '\n') trainfile.close()
def putoriginal(fname, img): ori_img = highgui.cvLoadImage (fname) ori_img_thumb = cv.cvCreateImage(cv.cvSize(ori_img.width/4, ori_img.height/4), 8,3) cv.cvResize(ori_img, ori_img_thumb) for x in range(ori_img_thumb.height): for y in range(ori_img_thumb.width): cv.cvSet2D(img, x, y, cv.cvGet2D(ori_img_thumb, x, y)) return
def __init__(self, entry): self.id = entry.id filename = entry.filepath self.image = highgui.cvLoadImage(filename) if not self.image: raise SystemError('This picture is not parsable by opencv :'+filename) self.setSize(self.image.width, self.image.height) if entry.getSize() is None: entry.setSize(cv.cvGetSize(self.image))
def putoriginal(fname, img): ori_img = highgui.cvLoadImage(fname) ori_img_thumb = cv.cvCreateImage( cv.cvSize(ori_img.width / 4, ori_img.height / 4), 8, 3) cv.cvResize(ori_img, ori_img_thumb) for x in range(ori_img_thumb.height): for y in range(ori_img_thumb.width): cv.cvSet2D(img, x, y, cv.cvGet2D(ori_img_thumb, x, y)) return
def ros2cv(image): if image.colorspace == 'mono8': format = 'L' else: format = 'RGB' pil_image = Image.fromstring(format, (image.width, image.height), image.data) pil_image.save('ros2cv.bmp', 'BMP') cvim = highgui.cvLoadImage('ros2cv.bmp') return cvim
def __FindHarris(self, filename): #find the corners of images, and save all corner points in self.vKeyPoints self.img = highgui.cvLoadImage (filename) greyimg = cv.cvCreateImage(cv.cvSize(self.img.width, self.img.height), 8,1) w = cv.cvGetSize(self.img).width h = cv.cvGetSize(self.img).height image = cv.cvCreateImage(cv.cvGetSize(self.img), cv.IPL_DEPTH_32F, 1) cv.cvConvert(image, greyimg) self.cornerimg = cv.cvCreateImage(cv.cvGetSize(self.img), cv.IPL_DEPTH_32F, 1) cv.cvCornerHarris(image, self.cornerimg, 11,5,0.1)
def static_test(): """Takes a full colour numpy image""" from opencv import highgui image = highgui.cvLoadImage( "/usr/share/doc/opencv-doc/examples/c/lena.jpg") result = adaptors.Ipl2NumPy(process_image(image)) imshow(result) savefig("harris_scipy_static.png", transparent=True) show()
def static_test(): """Takes a full colour numpy image""" from opencv import highgui image = highgui.cvLoadImage("/usr/share/doc/opencv-doc/examples/c/lena.jpg") result = adaptors.Ipl2NumPy(process_image(image)) imshow(result) savefig("harris_scipy_static.png", transparent=True) show()
def _detect(image): """ Detects faces on `image` Parameters: @image: image file path Returns: [((x1, y1), (x2, y2)), ...] List of coordenates for top-left and bottom-right corner """ # the OpenCV API says this function is obsolete, but we can't # cast the output of cvLoad to a HaarClassifierCascade, so use # this anyways the size parameter is ignored frame = cvLoadImage(image) if not frame: return [] img = cvCreateImage(cvSize(frame.width, frame.height), IPL_DEPTH_8U, frame.nChannels) cvCopy(frame, img) # allocate temporary images gray = cvCreateImage((img.width, img.height), COPY_DEPTH, COPY_CHANNELS) width, height = (cvRound(img.width / IMAGE_SCALE), cvRound(img.height / IMAGE_SCALE)) small_img = cvCreateImage((width, height), COPY_DEPTH, COPY_CHANNELS) storage = cvCreateMemStorage(0) try: # convert color input image to grayscale cvCvtColor(img, gray, CV_BGR2GRAY) # scale input image for faster processing cvResize(gray, small_img, CV_INTER_LINEAR) cvEqualizeHist(small_img, small_img) coords = [] for haar_file in CASCADES: cascade = cvLoadHaarClassifierCascade(haar_file, cvSize(1, 1)) if cascade: faces = cvHaarDetectObjects(small_img, cascade, storage, HAAR_SCALE, MIN_NEIGHBORS, HAAR_FLAGS, MIN_SIZE) or [] for face_rect in faces: # the input to cvHaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints x, y = face_rect.x, face_rect.y pt1 = (int(x * IMAGE_SCALE), int(y * IMAGE_SCALE)) pt2 = (int((x + face_rect.width) * IMAGE_SCALE), int((y + face_rect.height) * IMAGE_SCALE)) coords.append((pt1, pt2)) finally: cvClearMemStorage(storage) return coords
def run(): filename = 'C:\\Documents and Settings\\rmccormack\\Desktop\\work_projects\\openCV\\test\\test1.jpg' im = hg.cvLoadImage(filename) if not im: print "Error opening %s" % filename sys.exit(-1) im2 = opencv.cvCreateImage(opencv.cvGetSize(im), 8, 4) opencv.cvCvtColor(im, im2, opencv.CV_BGR2BGRA) buffer = numpy.fromstring(im2.imageData, dtype=numpy.uint32).astype(numpy.float32) buffer.shape = (im2.width, im2.height) return buffer
def resizeImage(self, image_location, ouput_location, size): """ resizes the image to a rectangle with the given size and saves it """ width = size height = size input_image = highgui.cvLoadImage(image_location, 1) # flag: >0 the loaded image is forced to be a 3-channel color image output_image = cv.cvCreateImage(cv.cvSize(cv.cvRound(width), cv.cvRound(height)), 8, 3); cv.cvResize(input_image, output_image, cv.CV_INTER_LINEAR); highgui.cvSaveImage(ouput_location, output_image) # save the image to file
def main(videofilename): faces = Faces(videofilename) for i, f, totframes in common.video.frames(videofilename): # for i, f, totframes in common.video.frames(videofilename, maxframes=1000): print >> sys.stderr, "Processing %s, image %s" % (f, common.str.percent(i+1, totframes)) print >> sys.stderr, stats() image = cvLoadImage(f) faces.set_dimensions(image.width, image.height) faces.add_frame(i, detect_faces(image)) if i % 100 == 0 and i != 0: print >> sys.stderr, common.json.dumps(faces.__getstate__()) print common.json.dumps(faces.__getstate__())
def main(videofilename): faces = Faces(videofilename) for i, f, totframes in common.video.frames(videofilename): # for i, f, totframes in common.video.frames(videofilename, maxframes=1000): print >> sys.stderr, "Processing %s, image %s" % ( f, common.str.percent(i + 1, totframes)) print >> sys.stderr, stats() image = cvLoadImage(f) faces.set_dimensions(image.width, image.height) faces.add_frame(i, detect_faces(image)) if i % 100 == 0 and i != 0: print >> sys.stderr, common.json.dumps(faces.__getstate__()) print common.json.dumps(faces.__getstate__())
def __FindCorner(self, filename): #find the corners of images, and save all corner points in self.vKeyPoints self.img = highgui.cvLoadImage (filename) greyimg = cv.cvCreateImage(cv.cvSize(self.img.width, self.img.height), 8,1) hsvimg = cv.cvCreateImage(cv.cvGetSize(self.img), 8, 3) cv.cvCvtColor(self.img, hsvimg, cv.CV_RGB2HSV) cv.cvCvtColor (hsvimg, greyimg, cv.CV_BGR2GRAY) eigImage = cv.cvCreateImage(cv.cvGetSize(greyimg), cv.IPL_DEPTH_32F, 1) tempImage = cv.cvCreateImage(cv.cvGetSize(greyimg), cv.IPL_DEPTH_32F, 1) self.points = cv.cvGoodFeaturesToTrack(greyimg, eigImage,tempImage, 2000, 0.01, 5, None, 3,0,0.01 ) self.points2 = cv.cvFindCornerSubPix(greyimg, self.points,cv.cvSize(20, 20), cv.cvSize(-1, -1), cv.cvTermCriteria(cv.CV_TERMCRIT_ITER |cv.CV_TERMCRIT_EPS, 20, 0.03)) cv.cvReleaseImage(eigImage) cv.cvReleaseImage(tempImage)
def main(): """ Just the test This method is a god resource on how to handle the results """ filename = sys.argv[1] image = highgui.cvLoadImage (filename) print "DO NOT EXPECT THE RUNNING TIME OF THIS TEST TO BE REPRESENTATIVE!" print "" print "THRESHOLDS AND EVERYTHING ELSE ARE HARDCODED!" cutRatios = [0.6667, lib.PHI, 0.6] settings = Settings(cutRatios) # Run the analysis with the above settings comps = naiveMethod.analyzeImage(image, settings) # This is just for drawing the results # The below methods can probably be combined but don't bother # {{{ # Get and draw the cuts cuts = {} for ratio in settings.cutRatios: cuts[str(ratio)] = lib.findMeans(cv.cvGetSize(image), ratio) for ratio in cuts: lib.drawLines(image, None, cuts[ratio], lib.getRandomColor()) # Get and draw the components for ratio in comps: for cut in comps[ratio]: lib.drawBoundingBoxes(image, comps[ratio][cut]) # }}} winname = "Failure" highgui.cvNamedWindow (winname, highgui.CV_WINDOW_AUTOSIZE) while True: highgui.cvShowImage (winname, image) c = highgui.cvWaitKey(0) if c == 'q': print "Exiting ..." print "" sys.exit(0)
def main(): """ Just the test This method is a god resource on how to handle the results """ filename = sys.argv[1] image = highgui.cvLoadImage (filename) cutRatios = [0.61] settings = Settings(cutRatios) image = highgui.cvLoadImage (filename) thickness = 4 settings.setMarginPercentage(0.025) cutNo = int(sys.argv[2]) cut = lib.findMeans(cv.cvGetSize(image), settings.cutRatios[0])[cutNo] # Get the BW edge image edgeImage = naiveMethod.getEdgeImage(image, settings) (blobImg, comp) = naiveMethod.analyzeCut(image, edgeImage, cut, settings, 'True') #liste af liste gridPointsList = grid.gridIt(blobImg, comp) #print gridPointsList points = centerOfMass(gridPointsList) #(x,y) for point in points: cv.cvLine(image, cv.cvPoint(point, 0), cv.cvPoint(point,600), COL_GREEN) lib.drawBoundingBoxes(image, comp) #highgui.cvSaveImage('floodfillbilledet.png', blobImg) #highgui.cvSaveImage('boindingboxbilledet.png', boxxImg) showImage(image, 'name')
def HarrisPoints(self, imgfile): self.points = [] self.drawimg = highgui.cvLoadImage (imgfile) c = 1 try: gray = cv.cvCreateImage (cv.cvGetSize (self.drawimg), 8, 1) cv.cvCvtColor(self.drawimg, gray, cv.CV_BGR2GRAY) eig = cv.cvCreateImage (cv.cvGetSize (self.drawimg), 32, 1) tmpimg = cv.cvCreateImage (cv.cvGetSize (self.drawimg), 32, 1) p = cv.cvGoodFeaturesToTrack(gray, eig, tmpimg, 100, 0.1, 20, None, 7, 1, 0.04 ) for x in p: cv.cvCircle( self.drawimg, x, 3, cv.CV_RGB(0,255,0), 8, 0 ); self.points.append(x) except Exception,e: print e print 'ERROR: problem handling '+ imgfile
def detect_faces_on(path): faces = [] image = cvLoadImage(path) # convert to grayscale for faster results grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1) cvCvtColor(image, grayscale, CV_BGR2GRAY) # smooth picture for better results cvSmooth(grayscale, grayscale, CV_GAUSSIAN, 3, 3) storage = cvCreateMemStorage(0) cvClearMemStorage(storage) cvEqualizeHist(grayscale, grayscale) cascade_files = [ # ('/usr/share/opencv/haarcascades/haarcascade_eye_tree_eyeglasses.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_lowerbody.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_mcs_mouth.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_profileface.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_eye.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_mcs_eyepair_big.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_mcs_nose.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_righteye_2splits.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_fullbody.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_mcs_eyepair_small.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_mcs_righteye.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_upperbody.xml', (50, 50)), ('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt_tree.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_lefteye_2splits.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_mcs_lefteye.xml', (50, 50)), # ('/usr/share/opencv/haarcascades/haarcascade_mcs_upperbody.xml', (50, 50)), # ('parojos_22_5.1.xml', (22, 5)), # ('Mouth.xml', (22, 15)), ] for cascade_file, cascade_sizes in cascade_files: cascade = cvLoadHaarClassifierCascade(os.path.join(cascade_file), cvSize(1, 1)) faces += cvHaarDetectObjects(grayscale, cascade, storage, HAAR_SCALE, HAAR_NEIGHBORS, CV_HAAR_DO_CANNY_PRUNING, cvSize(*cascade_sizes)) return [{'x': f.x, 'y': f.y, 'w': f.width, 'h': f.height} for f in faces]
def __init__(self, filename, scale): self.list = [] self.scale = scale try: self.image = highgui.cvLoadImage(filename, highgui.CV_LOAD_IMAGE_GRAYSCALE) #Deal with borders/edges and performing analyses. self.n = (self.image.width - (scale + 2)) * (self.image.height - (scale + 2)) if(type(self.image) == NoneType): print >> sys.stderr, " The filename provided does not exist." sys.exit(1) except IndexError as e: print >> sys.stderr, " Please provide the name of a local image." sys.exit(1) dict.__init__(self) self.default = None self.copyImage(self.image) self.E = {}
def HarrisPoints(self, imgfile): self.points = [] self.drawimg = highgui.cvLoadImage(imgfile) c = 1 try: gray = cv.cvCreateImage(cv.cvGetSize(self.drawimg), 8, 1) cv.cvCvtColor(self.drawimg, gray, cv.CV_BGR2GRAY) eig = cv.cvCreateImage(cv.cvGetSize(self.drawimg), 32, 1) tmpimg = cv.cvCreateImage(cv.cvGetSize(self.drawimg), 32, 1) p = cv.cvGoodFeaturesToTrack(gray, eig, tmpimg, 100, 0.1, 20, None, 7, 1, 0.04) for x in p: cv.cvCircle(self.drawimg, x, 3, cv.CV_RGB(0, 255, 0), 8, 0) self.points.append(x) except Exception, e: print e print 'ERROR: problem handling ' + imgfile
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 __findMaxSize(self): """ Face images are rectangles, find the maximum rectangle size """ max_width = -1 #max_ratio # height/width ratio cropped_files = self.getCroppedFaceImages() for fname in cropped_files: # cropped faces images have the following filename-format [0-9]*4_cropface_[0-9]*4.jpg print fname image_location = self.cropped_faces_dir + "\\" + fname image = highgui.cvLoadImage(image_location, 1) # a cropped non-normalized image print "width: " + str(image.width) print "height: " + str(image.height) ratio = image.height/image.width print "ratio: " + str(ratio) if image.width > max_width: max_width = image.width return max_width
def __init__(self, filename): print "Made pxNodeArray" try: image = highgui.cvLoadImage(filename, highgui.CV_LOAD_IMAGE_GRAYSCALE) if(type(image) == NoneType): print >> sys.stderr, " The filename provided does not exist." sys.exit(1) except IndexError as e: print >> sys.stderr, " Please provide the name of a local image." sys.exit(1) dict.__init__(self) self.default = None self.copyImage(image) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: print "None" return self.default
def normalizeFaces(self, useSize=True, size=None): """ Normalizes all the images in the cropped_faces_dir """ max_size = 0 if size == None: # use default size if none size = DEFAULT_FACE_SIZE if useSize == False: # use the maximum face size found max_size = self.__findMaxSize() else: max_size = size # loop over the original images cropped_files = self.getCroppedFaceImages() self.filecount = len(cropped_files) if self.startCallback is not None: self.startCallback(self.filecount) print "Normalizing " + str(self.filecount) + " images" for index, fname in enumerate(cropped_files): image_location = self.cropped_faces_dir + "\\" + fname image = highgui.cvLoadImage(image_location, 1) # a cropped non-normalized image p = re.compile(CROPFACE_FILENAME_PATTERN) m = p.match(fname) prefix = m.group("prefix") image_index = m.group("image_index") face_index = m.group("face_index") norm_image = self.__normImage(image, max_size) # normalize the image norm_filename = prefix + "_" + image_index + "_norm_" + face_index + ".jpg" location = self.norm_dir + "\\" + norm_filename highgui.cvSaveImage(location, norm_image) # save the image to file if self.iterCallback is not None: self.iterCallback(index)
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 prepare(self): log.info('prepare(): trainpath: %s, symbolpath: %s' % colorize((self.trainpath, self.symbolpath))) trainfile = open(self.trainpath, 'w') filter = re.compile(SYMBOL_FILTER) symbols = [] for name in os.listdir(self.symbolpath): if filter.match(name): symbols.append(name) trainfile.write('%d %d %d\n' % (len(symbols), self.input, self.output)) for name in symbols: img = cvLoadImage(SYMBOLS_PATH + self.site + '/' + name, CV_LOAD_IMAGE_GRAYSCALE) data = self.getdata(img) trainfile.write('%s\n' % ' '.join(map(str, data))) c = name[0] n = self.charset.index(c) trainfile.write('-1 ' * n + '1' + ' -1' * (self.output - n - 1) + '\n') trainfile.close()
def imread(fname): return cvLoadImage(fname, -1)
def main(argv=None): if argv is None: argv = sys.argv if len(argv) <= 1 or argv[1] is "-": im = DEFAULT_INPUT_IMAGE else: im = argv[1] if len(argv) <= 2 or argv[2] is "-": psize = DEFAULT_PIXEL_SCALE else: psize = int(argv[2]) if len(argv) <= 3 or argv[3] is "-": h = DEFAULT_OUTPUT_HEIGHT else: h = int(argv[3]) if len(argv) <= 4 or argv[4] is "-": w = DEFAULT_OUTPUT_WIDTH else: w = int(argv[4]) if len(argv) <= 5 or argv[5] is "-": serialport = DEFAULT_SERIAL_PORT else: serialport = argv[5] # declair globals global ser, output, curX, curY, last_dir # Open serial connection if serialport is not -1: ser = serial.Serial(serialport, 9600, timeout=1) else: ser = 0 last_dir = [None,None] # Print starting time stamp print time.strftime ('Start Time: %H:%M:%S') # Load the image image = highgui.cvLoadImage(im) # Create the output image curX = 0 curY = 0 output = opencv.cvCreateImage(opencv.cvSize(w,h), opencv.IPL_DEPTH_8U, 3) opencv.cvZero(output) opencv.cvNot(output,output) # Draw the image drawImage(image,h,w,psize) # Show the image displayImage(output) # Print end time stamp print time.strftime ('End Time: %H:%M:%S') # loop while(1): events = pygame.event.get() for event in events: if event.type == QUIT or (event.type == KEYDOWN): exit()
def static_test(): image_filename = "/usr/share/doc/opencv-doc/examples/c/lena.jpg" i = highgui.cvLoadImage(image_filename) result = harrisResponse(i) highgui.cvSaveImage("harris_response_lena_opencv.jpg", result) return result
def testGaussianBlur(): """Test that the guassian blur function gives the exact same output in Python and in C++ with OpenCV and ideally with SciPy. Can run this test with: nosetests --with-doctest blur_scipy.py -v """ from pylab import imread from opencv import highgui import blur_opencv # a seperate file with the opencv gaussian operation # Using Lena image create tests image. image_filename = "/usr/share/doc/opencv-doc/examples/c/lena.jpg" i = highgui.cvLoadImage(image_filename) # Carry out the filtering py_scipy = mlGaussianBlur( i) # note - it is decorated to convert between cvMat and NumPy py_scipy2 = gaussianBlur(i) py_opencv = blur_opencv.gaussianBlur(i) # Save the outputs as jpg files highgui.cvSaveImage("gaussian_scipy_iir.jpg", py_scipy) highgui.cvSaveImage("gaussian_scipy_ndfilt.jpg", py_scipy2) highgui.cvSaveImage("gaussian_opencv.jpg", py_opencv) # Load in the image data with scipy python_opencv_image = imread("gaussian_opencv.jpg") python_scipy_image = imread("gaussian_scipy_ndfilt.jpg") python_scipy2_image = imread("gaussian_scipy_iir.jpg") diff = uint8( abs( python_opencv_image.astype(float) - python_scipy_image.astype(float))) diff2 = uint8( abs( python_opencv_image.astype(float) - python_scipy2_image.astype(float))) diff3 = uint8( abs( python_scipy_image.astype(float) - python_scipy2_image.astype(float))) # For visual inspection: from pylab import show, imshow, figure, subplot, title figure() subplot(1, 3, 1) title("The OpenCV Output (Py and C++)") imshow(python_opencv_image) subplot(1, 3, 2) title("SciPy: IIR filter") imshow(python_scipy_image) subplot(1, 3, 3) title("SciPy: ndimage.filters.gaussian_filter") imshow(python_scipy2_image) figure() subplot(1, 3, 1) imshow(diff) subplot(1, 3, 2) imshow(diff2) subplot(1, 3, 3) imshow(diff3) from misc import plot_seperate_rgb plot_seperate_rgb(diff) plot_seperate_rgb(diff3) show() # Check that the sum of all differences at each point is 0 print sum(python_opencv_image.flatten() - python_scipy_image.flatten())
cv.cvSetZero (col_edge) # copy edge points cv.cvCopy (image, col_edge, edge) # show the image highgui.cvShowImage (win_name, col_edge) if __name__ == '__main__': filename = "rr.jpg" if len(sys.argv)>1: filename = sys.argv[1] # load the image gived on the command line image = highgui.cvLoadImage (filename) if not image: print "Error loading image '%s'" % filename sys.exit(-1) # create the output image col_edge = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 3) # convert to grayscale gray = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 1) edge = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 1) cv.cvCvtColor (image, gray, cv.CV_BGR2GRAY) # create the window highgui.cvNamedWindow (win_name, highgui.CV_WINDOW_AUTOSIZE)
# copy edge points cv.cvCopy(image, col_edge, edge) # show the image highgui.cvShowImage(win_name, col_edge) if __name__ == '__main__': filename = "../c/fruits.jpg" if len(sys.argv) > 1: filename = sys.argv[1] # load the image gived on the command line image = highgui.cvLoadImage(filename) if not image: print "Error loading image '%s'" % filename sys.exit(-1) # create the output image col_edge = cv.cvCreateImage(cv.cvSize(image.width, image.height), 8, 3) # convert to grayscale gray = cv.cvCreateImage(cv.cvSize(image.width, image.height), 8, 1) edge = cv.cvCreateImage(cv.cvSize(image.width, image.height), 8, 1) cv.cvCvtColor(image, gray, cv.CV_BGR2GRAY) # create the window highgui.cvNamedWindow(win_name, highgui.CV_WINDOW_AUTOSIZE)
laserTcam = tr.composeHomogeneousTransform(rt, disp) trans = tr.invertHomogeneousTransform(laserTcam) return trans #seeds = np.array([0.018, -0.057, 0.015, 91.2, 90.8, 0.0]) #seeds = np.array([0.013, -0.027, 0.025, 91.2, 92.8, 0.0]) #seeds = np.array([0.013, -0.032, 0.01, 91.4, 93.2, 0.0]) #seeds = np.array([ 0.003, 0.1 , -0.02, 89.8, 89.8, 90.0, 0]) seeds = np.array([-0.087, 0.105, 0.01, 89.8, 89.8, 90.0, 0]) #deltas = np.array([0.005, 0.005, 0.005, 0.1, 0.1, 0.1, 0.1]) #seeds = np.array([0.061, 0.032, -0.035, 0.8, 0.9, -1.7, 3.1 ]) deltas = np.array([0.001, 0.001, 0.001, 0.1, 0.1, 0.1, 0.1]) #self.cam_names = ['Ry_0', 'Rz_0', 'Rx_-90', 'Rz_-90', 'dx', 'dy', 'dz'] names = ['x_disp', 'y_disp', 'z_disp', 'rotX', 'rotZ', 'rotX', 'rotZ'] img = hg.cvLoadImage(image_filename) raw_laser_scans = ut.load_pickle(point_cloud_filename) #if raw_laser_scans.__class__ == ().__class__: poses, scans = raw_laser_scans['laserscans'][0] points_cloud_laser = p3d.generate_pointcloud(poses, scans, math.radians(-180), math.radians(180), 0, .035, max_dist=5, min_dist=.2) #else: # points_cloud_laser = raw_laser_scans import webcam_config as cc
elif sys.argv[i] == "--noGUI": GUI = 0 capture = init_cam() i = i + 1 elif sys.argv[i] == "--fps": capture = init_cam() highgui.cvSetCaptureProperty(capture, highgui.CV_CAP_PROP_FPS, int(sys.argv[i + 1])) i = i + 1 # check that capture device is OK if not capture: print "Error opening capture device" sys.exit(1) # Load config frameGrayBg = highgui.cvLoadImage("background.bmp", highgui.CV_LOAD_IMAGE_GRAYSCALE) logfile = open('config', 'r') nb_div_zone[0] = int(logfile.readline()) seuil_binary[0] = int(logfile.readline()) gain[0] = int(logfile.readline()) param_liss[0] = int(logfile.readline()) param2_liss[0] = int(logfile.readline()) logfile.close() # a small welcome print "OpenCV Python - multitouch" print "OpenCV version: %s (%d, %d, %d)" % ( cv.CV_VERSION, cv.CV_MAJOR_VERSION, cv.CV_MINOR_VERSION, cv.CV_SUBMINOR_VERSION) ############################ GUI Config #####################################
fy = cp['focal_length_y_in_pixels'] cam_proj_mat = np.matrix([[fx, 0, 0, 0], [0, fy, 0, 0], [0, 0, 1, 0]]) cam_centers = ( cp['optical_center_x_in_pixels'], cp['optical_center_y_in_pixels'] ) #take image and scan import scanner import configuration #id = '2009Nov04_144041' id = '2009Nov04_135319' cfg = configuration.configuration('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/labeling') img = hg.cvLoadImage(cfg.path + '/data/' + id + '_image.png') thok_dict = ut.load_pickle(cfg.path + '/data/' + id + '_laserscans.pkl') #cfg = configuration.configuration('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/calib') #cfg.webcam_id = 0 #sc = scanner.scanner(cfg) #sc.capture_and_save('calib', False) #img = hg.cvLoadImage('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/calib/data/calib_image.png') #thok_dict = ut.load_pickle('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/calib/data/calib_laserscans.pkl') poses, scans = thok_dict['laserscans'][0] points_cloud_laser = p3d.generate_pointcloud(poses, scans, math.radians(-180), math.radians(180), 0, .035, max_dist=5.0, min_dist=.1) c = laser_cam_callib.Callib(cameraTlaser, seeds, deltas, names, points_cloud_laser, img, cam_proj_mat, cam_centers,1, id) while not c.reDraw(): tmp = 1
def np2cv(im): image = np2pil(im) image.save('test.bmp', 'BMP') cvim = highgui.cvLoadImage('test.bmp') return cvim
cv.CV_RGB(0, 0, 255), 1, cv.CV_AA, 0) # Show image. HighGUI use. highgui.cvShowImage("Result", image04) if __name__ == '__main__': argc = len(sys.argv) filename = "../c/stuff.jpg" if (argc == 2): filename = sys.argv[1] slider_pos = 70 # load image and force it to be grayscale image03 = highgui.cvLoadImage(filename, 0) if not image03: print "Could not load image " + filename sys.exit(-1) # Create the destination images image02 = cv.cvCloneImage(image03) image04 = cv.cvCloneImage(image03) # Create windows. highgui.cvNamedWindow("Source", 1) highgui.cvNamedWindow("Result", 1) # Show the image. highgui.cvShowImage("Source", image03)
hg.cvNamedWindow('eigen value 1', 1) hg.cvNamedWindow('eigen value 2', 1) hg.cvShowImage('eigen value 1', l1cv) hg.cvShowImage('eigen value 2', l2cv) while True: k = hg.cvWaitKey(33) if k == ' ': return if k == 'x': exit() if __name__ == '__main__': #import pdb #hg.cvNamedWindow('win', 1) im = hg.cvLoadImage('/home/haidai/svn/robot1/src/projects/08_03_dog_commands/dragonfly_color_calibration/untitled folder/camera_image.png') #hg.cvShowImage('win', im) for i in range(40): s = (i+1) * 2 print s eig_tex_np = eigen_texture(im, blocksize=s, filtersize=3) visualize(eig_tex_np) # pdb.set_trace() # def texture_features(self, block_size=5, filter_size=3): # """ # Calculates the texture features associated with the image. # block_size gives the size of the texture neighborhood to be processed # filter_size gives the size of the Sobel operator used to find gradient information
# detect objects faces = opencv.cvHaarDetectObjects(grayscale, cascade, storage, 1.2, 2, opencv.CV_HAAR_DO_CANNY_PRUNING, opencv.cvSize(100, 100)) # eyes = opencv.cvHaarDetectObjects(grayscale, eye_cascade, storage, 1.2, 2, opencv.CV_HAAR_DO_CANNY_PRUNING, opencv.cvSize(60,60)) draw_bounding_boxes(faces, image, 127,255,0, 3) # draw_bounding_boxes(eyes, image, 255,127,0, 1) fps = 30.0 pygame.init() window = pygame.display.set_mode((640,480)) pygame.display.set_caption("Face-recognition Demo") screen = pygame.display.get_surface() #demo image preparation cv_im = highgui.cvLoadImage("demo.jpg") detect(cv_im) pil_im = Ipl2PIL(cv_im) def read_demo_image(): return pil_im while True: # Fixed demo for when you have no Webcam #im = read_demo_image() # UNCOMMENT this and comment out the demo when you wish to use webcam im = get_image() pil_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode) screen.blit(pil_img, (0,0))
def opencv_scale(filename, width, height): im = highgui.cvLoadImage(filename) newim = cv.cvCreateImage(cv.cvSize(width, height), 8, 3) cv.cvResize(im, newim, cv.CV_INTER_AREA) highgui.cvSaveImage("outcv.jpg", newim)
def Process(inFile, outFile): image1 = highgui.cvLoadImage(inFile,0) sz = cv.cvGetSize(image1) image2 = cv.cvCreateImage(sz, 8, 1) cv.cvConvertScale(image1, image2, 1.2, 0) highgui.cvSaveImage(outFile, image2)
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ## @author Hai Nguyen/[email protected] ##@package image_broadcaster # Broadcast image given on command line to topic 'image'. import rostools rostools.updatePath('gmmseg') import rospy import std_msgs.msg.Image as RImage import opencv.highgui as hg import opencv as cv import sys import time rospy.ready(sys.argv[0]) pub_channel = rospy.TopicPub('image', RImage) cv_image = hg.cvLoadImage(sys.argv[1]) cv.cvCvtColor(cv_image, cv_image, cv.CV_BGR2RGB) count = 1 while not rospy.isShutdown(): image = RImage(None, 'static', cv_image.width, cv_image.height, '', 'rgb24', cv_image.imageData) pub_channel.publish(image) print 'published', count count = count + 1 time.sleep(.3)
def setImage(self, filename): self.image = highgui.cvLoadImage(filename) if not self.image: raise SystemError('This picture is not parsable by opencv :'+filename)
def __init__(self, path=None): self.path = path try: self.iplimage = hg.cvLoadImage(self.path) except: raise AttributeError("could not load image file")
else: prev_row_sum = cv.cvmGet(row_sums,i-1,j) cv.cvmSet(row_sums,i,j,image_value+prev_row_sum) if(j == 0): cv.cvmSet(result,i,j,prev_row_sum+image_value) else: prev_result = cv.cvmGet(result,i,j-1) cv.cvmSet(result,i,j,prev_row_sum+image_value+prev_result) if(i == 0 and j == 0): print "image_value:",image_value print "prev_row_sum:",prev_row_sum return result image = highgui.cvLoadImage("Screenshot-Camera.png",1) iimg = IntegralImage(image) def draw_target(img, x, y): width = 10 color = cv.CV_RGB(0,255,0); size = cv.cvGetSize(img) #cv.cvSet2D(img,x,y,color); for i in range(width): for j in range(width): if i==0 or j==0 or j==9 or i==9: px = x + j - width/2 py = y + i - width/2
self.ann.create_from_file(self.netpath) log.info('load(): netpath: %s' % colorize(self.netpath)) def symbol(self, data): distr = self.ann.run(data) i = distr.index(max(distr)) smb = self.charset[i] log.debug('symbol(): distr: %s' % map(lambda el: round(el, 2), distr)) return smb def captcha(self, symbols): result = '' for smb in symbols: data = self.getdata(smb) result += self.symbol(data) log.info('captcha(): result: %s' % colorize(result)) return result if __name__ == '__main__': a = Analyzer(20, 30, '123456789') a.prepare('wmtake.trn', '/home/polzuka/inspirado/symbols/wmtake') a.train('wmtake.trn') a.load('/home/polzuka/inspirado/wmtake.ann') img = cvLoadImage('/home/polzuka/inspirado/symbols/wmtake/4_19.png', CV_LOAD_IMAGE_GRAYSCALE) print a.symbol(a.getdata(img)) img = cvLoadImage('/home/polzuka/inspirado/symbols/wmtake/9_15.png', CV_LOAD_IMAGE_GRAYSCALE) print a.symbol(a.getdata(img))