def simplest_color_balance(image, s1=0, s2=0, mask=None): #tick = time.time() UMAX = 255 copy = image.copy() layers = cv2.split(copy) for i, layer in enumerate(layers): hist = cv2.calcHist([layer], [0], mask, [UMAX + 1], [0, UMAX]) cumsum = hist.cumsum() size = cumsum[-1] lb = size * s1 / 100.0 ub = size * (1 - s2 / 100.0) # reinit borders left = bisect.bisect_left(cumsum, lb) right = bisect.bisect_right(cumsum, ub) if (right - left) <= 0: left = UMAX / 2 - 1 right = UMAX / 2 #print left, right # replacing values if left != 0: left_mask = cv2.inRange(layer, np.array(0), np.array(left)) cv.Set(cv.fromarray(layer), left, cv.fromarray(left_mask)) if right != UMAX: right_mask = cv2.inRange(layer, np.array(right), np.array(UMAX)) cv.Set(cv.fromarray(layer), right, cv.fromarray(right_mask)) layers[i] = layer layers = map(lambda x: cv2.normalize(x, x, 0, UMAX, cv2.NORM_MINMAX), layers) copy = cv2.merge(layers) #cv2.imshow('filter', copy) #tock = time.time() #print tock - tick return copy
def rangeGUI(): """ creates and displays a GUI for the range finder data Ranges window: shows range finder values as red lines coming from the center of the range finder HoughLines window: shows the result of using a Hough transformation on image containing the range values as points. """ global D init_GUI() # initialize images and windows D.dangerList = [] # Set up the danger point list # main loop while rospy.is_shutdown() == False: # loop through every angle for angle in range(REV): magnitude = MAG_SCALE * D.ranges[angle] x = int(CENTER + magnitude * cos(pi / 180 * (angle + ANGLE_OFFSET)) ) # find x and y coordinates based on the angle y = int(CENTER - magnitude * sin(pi / 180 * (angle + ANGLE_OFFSET))) # and the length of the line # put the danger points into the list if x > CENTER - 30 and x < CENTER + 30 and y < CENTER - 30 and y > CENTER - 90: D.dangerList.append((x, y)) if 0 < magnitude < MAX_MAG: # if data is within "good data" range # add line to the ranges image cv.Line(D.image, (CENTER, CENTER), (x, y), cv.RGB(255, 0, 0)) # add dot to image being used in Hough transformation cv.Line(D.hough, (x, y), (x, y), cv.RGB(255, 0, 0)) # wait and check for quit request key_code = cv.WaitKey(1) & 255 key_press = chr(key_code) if key_code == 27 or key_press == 'q': # if ESC or 'q' was pressed rospy.signal_shutdown("Quitting...") # find walls and add to image using Hough transformation findHoughLines() # show image with range finder data and calculated walls cv.ShowImage("Ranges", D.image) # show image used in Hough transformation if option is selected if SHOW_HOUGH: cv.ShowImage("HoughLines", D.color_dst) # clear the images for next loop cv.Set(D.image, cv.RGB(0, 0, 0)) cv.Set(D.hough, cv.RGB(0, 0, 0)) # clear the danger list for next loop D.dangerList = [] D.tank(0, 0) # stops the robot print "Quitting..."
def _computeBGDiff(self): self._flow.update( self._imageBuffer.getLast() ) n = len(self._imageBuffer) prev_im = self._imageBuffer[0] forward = None for i in range(0,n/2): if forward == None: forward = self._imageBuffer[i].to_next else: forward = forward * self._imageBuffer[i].to_next w,h = size = prev_im.size mask = cv.CreateImage(size,cv.IPL_DEPTH_8U,1) cv.Set(mask,0) interior = cv.GetSubRect(mask, pv.Rect(2,2,w-4,h-4).asOpenCV()) cv.Set(interior,255) mask = pv.Image(mask) prev_im = forward(prev_im) prev_mask = forward(mask) next_im = self._imageBuffer[n-1] back = None for i in range(n-1,n/2,-1): if back == None: back = self._imageBuffer[i].to_prev else: back = back * self._imageBuffer[i].to_prev next_im = back(next_im) next_mask = back(mask) curr_im = self._imageBuffer[n/2] prevImg = prev_im.asMatrix2D() curImg = curr_im.asMatrix2D() nextImg = next_im.asMatrix2D() prevMask = prev_mask.asMatrix2D() nextMask = next_mask.asMatrix2D() # Compute transformed images delta1 = sp.absolute(curImg - prevImg) #frame diff 1 delta2 = sp.absolute(nextImg - curImg) #frame diff 2 delta1 = sp.minimum(delta1,prevMask) delta2 = sp.minimum(delta2,nextMask) #use element-wise minimum of the two difference images, which is what # gets compared to threshold to yield foreground mask return sp.minimum(delta1, delta2)
def add_alpha_channel(bgr, alpha_val): w, h = cv.GetSize(bgr) bgra = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 4) alpha = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1) chan1 = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1) chan2 = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1) chan3 = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1) [cv.Set(c, 0) for c in [chan1, chan2, chan3, bgra, alpha]] cv.Split(bgr, chan1, chan2, chan3, None) cv.Set(alpha, (alpha_val)) cv.Merge(chan1, chan2, chan3, alpha, bgra) return bgra
def __init__(self, img): self.img = cv.fromarray(img) self.width = self.img.cols self.height = self.img.rows self.cannyImg = cv.CreateMat(self.height, self.width, cv.CV_8UC1) self.outputImg = cv.CreateMat(self.height, self.width, cv.CV_8UC3) self.integralImg = cv.CreateMat(self.height + 1, self.width + 1, cv.CV_32FC1) self.calculatedImg = cv.CreateMat(self.height, self.width, cv.CV_8UC1) cv.Canny(self.img, self.cannyImg, 40, 100) cv.Integral(self.cannyImg, self.integralImg) cv.Set(self.calculatedImg, 0) cv.Set(self.outputImg, 0)
def measure(im, blur, noise=None, debug=False): focus_points = blur[0] #is_noisy = noise[2] size = cv.GetSize(im) npixels = size[0] * size[1] #if focused_regions is None: # focused_regions = image.new_from(im) # cv.Set(focused_regions, 0) # groups = form_groups(focus_points, # estimated_size=min(max(int(len(npixels) / 1000), 2), 15)) # #groups = form_groups(points, threshold=max(cv.GetSize(im))/16) # #print 'groups', len(groups) # draw_groups(groups, focused_regions) im2 = cv.CloneImage(im) g = Grid(cv.GetSize(im2)) if debug: image.show(g.draw(im2), "Image with Grid + ROI") roi = image.new_from(im, nChannels=1) cv.Set(roi, 0) #g.draw_lines(roi, thickness=int(max(min((size[0] + size[1]) * 1/100.0, 255), 1))) g.draw_regions(roi) area = cv.Sum(roi)[0] (_, face_rects), face_score = faces.measure(im) face_block = image.new_from(im, nChannels=1) cv.Set(face_block, 0) for r in face_rects: r.draw(face_block, color=cv.RGB(255,255,255), thickness=cv.CV_FILLED) if debug: face_roi = cv.CloneImage(im) cv.Set(face_roi, 0, image.invert(roi)) cv.Set(face_roi, 0, image.invert(image.threshold(face_block, threshold=1))) image.show(face_block, "Faces in Binary") image.show(g.draw(face_roi), "Face + ROI") return (im, ( measure_focused_roi(im, roi, area, focus_points, debug), #measure_color_roi(im, roi, area, focus_points, debug), measure_contrast(im, debug), measure_saturation(im, debug), faces.measure(im, debug)[1], ))
def get_canny_img(img): size = sizeOf(img) plate = cv.CreateImage(size, 8, 1) cv.Set(plate, 255) for k in (50, 100,150,200,250): # k=100 edges = cv.CreateImage(size, 8, 1) cv.Canny(img, edges, k-20, k) # show_image(edges) if k >= 100: cv.Dilate(edges,edges) else: k+=50 # cv.Erode(edges,edges) cv.Set(plate, 255 - k, edges) return plate
def gen_image(self, size, color_value): color = self.parse_hex_color(color_value) if not color: raise ValueError('Color %s is not valid.' % color_value) img0 = cv.CreateImage(size, 8, 3) cv.Set(img0, color) return img0
def test_encode_decode_cv1(self): import cv fmts = [ cv.IPL_DEPTH_8U, cv.IPL_DEPTH_8S, cv.IPL_DEPTH_16U, cv.IPL_DEPTH_16S, cv.IPL_DEPTH_32S, cv.IPL_DEPTH_32F, cv.IPL_DEPTH_64F ] cvb_en = CvBridge() cvb_de = CvBridge() for w in range(100, 800, 100): for h in range(100, 800, 100): for f in fmts: for channels in (1, 2, 3, 4): original = cv.CreateImage((w, h), f, channels) cv.Set(original, (1, 2, 3, 4)) rosmsg = cvb_en.cv_to_imgmsg(original) newimg = cvb_de.imgmsg_to_cv(rosmsg) self.assert_( cv.GetElemType(original) == cv.GetElemType(newimg)) self.assert_( cv.GetSize(original) == cv.GetSize(newimg)) self.assert_( len(original.tostring()) == len(newimg.tostring()))
def high_freq(img, pct): f = float_version(img) cv.DFT(f, f, cv.CV_DXT_FORWARD) mask = cv.CreateImage( cv.GetSize(img), 8, 1) cv.Set(mask, 0) #cv.Set(mask, 255) w, h = cv.GetSize(img) dw = int(w*pct*0.5) dh = int(h*pct*0.5) #cv.Rectangle(mask, (0,0), (int(w*pct), int(h*pct)), 255, -1) #cv.Rectangle(mask, (int(w*pct), int(h*pct)), (w,h), 255, -1) cv.Rectangle(mask, (w/2-dw,h/2-dh), (w/2+dw,h/2+dh), 255, -1) cv.Set(f,0,mask) return f cv.DFT(f, f, cv.CV_DXT_INVERSE_SCALE) return f
def spin(self): time.sleep(1.0) started = time.time() counter = 0 cvim = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 1) ball_xv = 10 ball_yv = 10 ball_x = 100 ball_y = 100 cvb = CvBridge() while not rospy.core.is_shutdown(): cv.Set(cvim, 0) cv.Circle(cvim, (ball_x, ball_y), 10, 255, -1) ball_x += ball_xv ball_y += ball_yv if ball_x in [10, 630]: ball_xv = -ball_xv if ball_y in [10, 470]: ball_yv = -ball_yv self.pub.publish(cvb.cv_to_imgmsg(cvim)) time.sleep(0.03)
def measure_focused_roi(im, roi, area, focus_points, debug=False): g = Grid(cv.GetSize(im)) canvas = image.new_from(im) cv.Set(canvas, 0) focus_in_roi = image.And(focus_points, roi) if debug: image.show(focus_in_roi, "ROI + Focused Points") densities = [] points = convert_to_points(focus_in_roi) groups = form_groups(points, estimated_size=24, iter=5) for group in groups: ch = ConvexHull(map(lambda x: (x[0], x[1]), group)) ppp = ch.points_per_pixel() a = int(ppp * 255) ch.draw_filled_hull(canvas, rgb=(a,a,a)) if debug: image.show(canvas, "Focused Regions in ROI") quadrants = g.split_in_four(canvas) sums = [] for i,quad in enumerate(quadrants): sums.append(cv.Sum(quad)[0] / float(area/4)) arr = array(sums) print arr.mean(), arr.std() diff = max(sums) - min(sums) return diff, arr.std()
def repaintCCs(image, doRepaint=None, returnMask=False, resizeMask=True, doFillBackground=True, bgPoint=(0, 0), newcol=255, connectivity=4): if doRepaint is None: doRepaint = lambda comp, col: False resultMask = cv.CreateImage((image.width + 2, image.height + 2), image.depth, image.nChannels) tempMask = cv.CreateImage((image.width + 2, image.height + 2), image.depth, image.nChannels) visitMask = cv.CreateImage((image.width + 2, image.height + 2), image.depth, image.nChannels) cv.Zero(resultMask) cv.Zero(tempMask) cv.Zero(visitMask) if doFillBackground: cv.FloodFill(image, bgPoint, 0, 0, 0, connectivity + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), visitMask) for x in xrange(image.width): for y in xrange(image.height): if visitMask[y + 1, x + 1] == 255: continue comp = cv.FloodFill(image, (x, y), 0, 0, 0, connectivity + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), tempMask) region = shiftRect(comp[2], 1, 1) cv.SetImageROI(tempMask, region) cv.SetImageROI(visitMask, region) cv.Or(tempMask, visitMask, visitMask) if doRepaint(comp, image[y, x]): cv.SetImageROI(resultMask, region) cv.Or(tempMask, resultMask, resultMask) cv.ResetImageROI(resultMask) cv.Zero(tempMask) cv.ResetImageROI(tempMask) cv.ResetImageROI(visitMask) if returnMask: if resizeMask: return cap.getSubImage(resultMask, (1, 1, image.width, image.height)) else: return resultMask else: cv.SetImageROI(resultMask, (1, 1, image.width, image.height)) cv.Set(image, newcol, resultMask) return image
def setup(flipped, capture, thehandcolor): """Initializes camera and finds initial skin tone""" #creates initial window and prepares text color = (40, 0, 0) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0) textsize1 = (cv.GetSize(flipped)[0] / 2 - 150, cv.GetSize(flipped)[1] / 2 - 140) textsize2 = (cv.GetSize(flipped)[0] / 2 - 150, cv.GetSize(flipped)[1] / 2 - 110) point1 = (cv.GetSize(flipped)[0] / 2 - 25, cv.GetSize(flipped)[1] / 2 - 25) point2 = (cv.GetSize(flipped)[0] / 2 + 25, cv.GetSize(flipped)[1] / 2 + 25) #until Enter is pressed while (cv.WaitKey(10) != 10): #captures live video, and draws sub-box and text frame = cv.QueryFrame(capture) cv.Copy(frame, flipped) cv.Flip(flipped, flipped, 1) cv.Rectangle(flipped, point1, point2, color, 2) cv.PutText(flipped, "Put your hand in the box ", textsize1, font, color) cv.PutText(flipped, "and press enter", textsize2, font, color) cv.ShowImage("w2", flipped) #Creates sub-image inside box, and returns average color in box sub = cv.GetSubRect(flipped, (cv.GetSize(flipped)[0] / 2 - 25, cv.GetSize(flipped)[1] / 2 - 25, 50, 50)) cv.Set(thehandcolor, cv.Avg(sub)) return cv.Avg(sub)
def getData(): for i in range (0 , classes): for j in range (0, train_samples): if j < 10 : fichero = "OCR/"+str(i) + "/"+str(i)+"0"+str(j)+".pbm" else: fichero = "OCR/"+str(i) + "/"+str(i)+str(j)+".pbm" src_image = cv.LoadImage(fichero,0) prs_image = preprocessing(src_image, size, size) row = cv.GetRow(trainClasses, i*train_samples + j) cv.Set(row, cv.RealScalar(i)) row = cv.GetRow(trainData, i*train_samples + j) img = cv.CreateImage( ( size, size ), cv.IPL_DEPTH_32F, 1) cv.ConvertScale(prs_image,img,0.0039215, 0) data = cv.GetSubRect(img, (0,0, size,size)) row1 = cv.Reshape( data, 0, 1 ) cv.Copy(row1, row)
def show_shapes(shapes): """ Function to show all of the shapes which are passed to it """ cv.NamedWindow("Shape Model", cv.CV_WINDOW_AUTOSIZE) # Get size for the window max_x = int(max([pt.x for shape in shapes for pt in shape.pts])) max_y = int(max([pt.y for shape in shapes for pt in shape.pts])) min_x = int(min([pt.x for shape in shapes for pt in shape.pts])) min_y = int(min([pt.y for shape in shapes for pt in shape.pts])) i = cv.CreateImage((max_x - min_x + 20, max_y - min_y + 20), cv.IPL_DEPTH_8U, 3) cv.Set(i, (0, 0, 0)) for shape in shapes: r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) #r = 0 #g = 0 #b = 0 for pt_num, pt in enumerate(shape.pts): # Draw normals #norm = shape.get_normal_to_point(pt_num) #cv.Line(i,(pt.x-min_x,pt.y-min_y), \ # (norm[0]*10 + pt.x-min_x, norm[1]*10 + pt.y-min_y), (r, g, b)) cv.Circle(i, (int(pt.x - min_x), int(pt.y - min_y)), 2, (r, g, b), -1) cv.ShowImage("Shape Model", i)
def main(): root = "/Users/soswow/Documents/Face Detection/test/negative" # root = "/Users/soswow/Documents/Face Detection/test/sets/negative" # root = "/Users/soswow/Documents/Face Detection/test/edge_view/positive" # root = "/Users/soswow/Documents/Face Detection/test/sobel/positive" # root = "/Users/soswow/Documents/Face Detection/test/sets/positive" # root = "/Users/soswow/Documents/Face Detection/test/falses" for folder in os.listdir(root): path = p.join(root, folder) if p.isdir(path): sum = cv.CreateMat(32, 32, cv.CV_32F) cv.Zero(sum) k = 0 for path, _ in directory_files(path): try: img = cv.LoadImage(path, iscolor=False) except IOError: continue mat = cv.CreateMat(32, 32, cv.CV_32F) cv.Zero(mat) cv.Convert(cv.GetMat(img), mat) cv.Add(mat, sum, sum) k += 1 avg = cv.CreateMat(32, 32, cv.CV_32F) cv.Zero(avg) count = cv.CreateMat(32, 32, cv.CV_32F) cv.Zero(count) cv.Set(count, k) cv.Div(sum, count, avg) new_img = cv.CreateImage((32, 32), 8, 0) cv.Zero(new_img) cv.Convert(avg, new_img) cv.SaveImage(p.join(root, "%s-avg.png" % folder), new_img)
def getForegroundPixels(self, bgcolor=None): ''' @param bgcolor: The background color to use. Specify as an (R,G,B) tuple. Specify None for a blank/black background. @return: The full color foreground pixels on either a blank (black) background, or on a background color specified by the user. @note: You must call detect() before getForegroundPixels() to get updated information. ''' if self._fgMask == None: return None #binary mask selecting foreground regions mask = self._fgMask.asOpenCVBW() #full color source image image = self._annotateImg.copy().asOpenCV() #dest image, full color, but initially all zeros (black/background) # we will copy the foreground areas from image to here. dest = cv.CloneImage(image) if bgcolor == None: cv.SetZero(dest) else: cv.Set(dest, cv.RGB(*bgcolor)) cv.Copy(image, dest, mask) #copy only pixels from image where mask != 0 return pv.Image(dest)
def getAverageValues2(self, images): """ get the average values over all the images for every two images, divides the images by 2 then adds them together """ if len(images) == 0: return None if len(images) == 1: return images[0] width = images[0].width height = images[0].height # create image with only 2's # this will be used for division divisionImage = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1) cv.Set(divisionImage, 2) image1 = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1) image2 = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1) avgImage = cv.CloneImage(images[0]) for image in images: # divide images by 2 cv.Div(avgImage, divisionImage, image1) cv.Div(image, divisionImage, image2) # add them to get result cv.Add(image1, image2, avgImage) return avgImage
def removeBadBackground(seg): threshUp = cv.CreateImage(cv.GetSize(seg), cv.IPL_DEPTH_8U, 1) comparison = cv.CreateImage(cv.GetSize(seg), cv.IPL_DEPTH_8U, 1) visitMask = cv.CreateImage(cv.GetSize(seg), cv.IPL_DEPTH_8U, 1) ffMask = cv.CreateImage((seg.width + 2, seg.height + 2), cv.IPL_DEPTH_8U, 1) cv.Threshold(seg, threshUp, 1, 255, cv.CV_THRESH_BINARY) cv.Zero(visitMask) cv.Zero(ffMask) for x in xrange(seg.width): for y in xrange(seg.height): if seg[y, x] != 96 or visitMask[y, x] == 255: continue comp = cv.FloodFill(threshUp, (x, y), 0, 0, 0, 4 + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), ffMask) rect = comp[2] cv.SetImageROI(ffMask, cap.shiftRect(rect, 1, 1)) cv.OrS(ffMask, 1, ffMask) cv.SetImageROI(seg, rect) cv.SetImageROI(comparison, rect) cv.Cmp( seg, ffMask, comparison, cv.CV_CMP_EQ) # 'comparison' does not need to be zeroed later intersect = cv.CountNonZero(comparison) cv.SetImageROI(visitMask, rect) cv.Or(visitMask, ffMask, visitMask) cv.ResetImageROI(visitMask) if intersect == 0: cv.Set(seg, 0, ffMask) cv.Zero(ffMask) cv.ResetImageROI(seg) cv.ResetImageROI(ffMask) return seg
def recognise(image, addr, extras): result = "" x = image.width - 1 channels = getChannels(image) bestBounds = [] #cv.NamedWindow("pic", 1) #cv.NamedWindow("cols", 0) while len(result) < nSegs and x >= minW: x = cap.getBound(image, cap.CAP_BOUND_RIGHT, start=x) ratings = [] for w in xrange(minW, min(maxW + 1, x)): bounds = findBounds(image, x, w) subImage = cap.getSubImage(image, bounds) flags = findColors(subImage) for index, flag in enumerate(flags): if not flag: continue seg = getSegment(channels[index], image, bounds) seg = cap.flattenImage(adjustSize(seg, segSize)) guesses = ann.run(seg) charIndex = cap.argmax(guesses) ratings.append( (guesses[charIndex], charIndex, index, bounds, seg)) best = max(ratings, key=itemgetter(0)) result += charset[best[1]] bestChannel = channels[best[2]] cv.SetImageROI(bestChannel, best[3]) cv.Set(bestChannel, 96, bestChannel) cv.ResetImageROI(bestChannel) bestBounds.append(best[3]) bestW = best[3][2] x -= bestW #print ann.run(best[4]) cap.processExtras([cap.drawComponents(image, bestBounds)], addr, extras, cap.CAP_STAGE_RECOGNISE) return result[::-1]
def drawHistogram(self, image, chnum, hist_arr, plateaus): positions = (0, (self.Ihist.height + 10), 2 * self.Ihist.height + 20) colour_values = _blue, _green, _red colour = colour_values[chnum] Y = positions[chnum] cv.Set(self.Ihist, _trans) bin_w = cv.Round(float(self.Ihist.width) / self.hist_size) # min_value, max_value, pmin, pmax = cv.GetMinMaxHistValue(hist) X = image.width - self.Ihist.width rect = (X, Y, self.Ihist.width, self.Ihist.height) cv.SetImageROI(image, rect) scaling = self.Ihist.height / max(hist_arr) hist_arr *= scaling for i, v in enumerate(hist_arr): cv.Rectangle(self.Ihist, (i * bin_w, self.Ihist.height), ((i + 1) * bin_w, self.Ihist.height - round(v)), colour, -1, 8, 0) for i in plateaus[chnum]: cv.Rectangle( self.Ihist, (i * bin_w, self.Ihist.height), ((i + 1) * bin_w, self.Ihist.height - round(hist_arr[i])), _white, -1, 8, 0) cv.AddWeighted(image, 1 - self.hist_visibility, self.Ihist, self.hist_visibility, 0.0, image) cv.ResetImageROI(image)
def findCCs(image, erasecol=0, doContinue=None, doSkip=None, bRange=0, connectivity=8): """ Finds all connected components in the image. doContinue is a function applied to the color of every new pixel in the image. If it is true, this pixel is ignored. Default: <= 128 doSkip is a function applied to every new connected component found by the function. If it is true, this component will not be included in the result. Default: do not skip anything. """ if doContinue is None: doContinue = lambda col: col <= 128 if doSkip is None: doSkip = lambda comp: False mask = cv.CreateImage((image.width + 2, image.height + 2), cv.IPL_DEPTH_8U, 1) cv.Zero(mask) components = [] for x in range(image.width): for y in range(image.height): if doContinue(image[y, x]): continue comp = cv.FloodFill(image, (x, y), 0, bRange, bRange, connectivity + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), mask) # here 3rd argument is ignored region = shiftRect(comp[2], 1, 1) if not doSkip(comp): seg = cvext.getSubImage(mask, region) components.append((comp[0], comp[1], comp[2], seg)) cv.SetImageROI(image, comp[2]) cv.SetImageROI(mask, region) cv.Set(image, erasecol, mask) cv.Zero(mask) cv.ResetImageROI(image) cv.ResetImageROI(mask) return components
def blockfacemask(bgrimg): global lastrects rects = detect_faces(bgrimg) rects = addheights(rects) newimg = im.newgray(bgrimg) cv.Set(newimg, 255) if rects: lastrects = rects else: rects = lastrects if rects: for rect in rects: cv.SetImageROI(newimg, rect) cv.Set(newimg, 0) cv.ResetImageROI(newimg) return newimg
def redraw_monocular(self, drawable): width, height = cv.GetSize(drawable.scrib) display = cv.CreateMat(max(480, height), width + 100, cv.CV_8UC3) cv.Zero(display) cv.Copy(drawable.scrib, cv.GetSubRect(display, (0, 0, width, height))) cv.Set(cv.GetSubRect(display, (width, 0, 100, height)), (255, 255, 255)) self.buttons(display) if not self.c.calibrated: if drawable.params: for i, (label, lo, hi, progress) in enumerate(drawable.params): (w, _), _ = cv.GetTextSize(label, self.font) cv.PutText(display, label, (width + (100 - w) / 2, self.y(i)), self.font, (0, 0, 0)) color = (0, 255, 0) if progress < 1.0: color = (0, int(progress * 255.), 255) cv.Line(display, (int(width + lo * 100), self.y(i) + 20), (int(width + hi * 100), self.y(i) + 20), color, 4) else: cv.PutText(display, "lin.", (width, self.y(0)), self.font, (0, 0, 0)) linerror = drawable.linear_error if linerror < 0: msg = "?" else: msg = "%.2f" % linerror #print "linear", linerror cv.PutText(display, msg, (width, self.y(1)), self.font, (0, 0, 0)) self.show(display)
def anaglyph(left_color, right_color, correction): #create oversized image #result = cv.CreateImage(cv.GetSize(right_color), cv.IPL_DEPTH_8U, 4) w, h = cv.GetSize(left_color) bgra = cv.CreateImage((w * 2, h), cv.IPL_DEPTH_8U, 4) cv.Set(bgra, 0) right_bgra = add_alpha_channel(right_color, round(255 / 2.)) #cyan (remove red?) left_bgra = add_alpha_channel(left_color, round(255 / 2.)) #red (remove blue?, green?) #remove blue & green from left => red left_red = remove_channels(left_bgra, [0, 1]) #remove red from right_bgra => cyan right_cyan = remove_channels(right_bgra, [2]) if correction < 0: left_area = cv.GetSubRect(bgra, (-correction, 0, w, h)) right_area = cv.GetSubRect(bgra, (0, 0, w, h)) valid_area = cv.GetSubRect(bgra, (-correction, 0, w + correction, h)) else: #copy left & right onto bgra left_area = cv.GetSubRect(bgra, (0, 0, w, h)) right_area = cv.GetSubRect(bgra, (correction, 0, w, h)) valid_area = cv.GetSubRect(bgra, (correction, 0, w - correction, h)) cv.Add(left_red, left_area, left_area) cv.Add(right_cyan, right_area, right_area) #return right_cyan #return left_red #return left_bgra #return bgra return valid_area
def to_img(self, height=200, color=cv.RGB(0, 0, 0), offset=(0, 0), bg=(255, 255, 255)): im = cv.CreateImage((self.bins * self.scale, height), 8, 3) cv.Set(im, bg) return self.draw(im, color, offset=(0, 0))
def cutLetters(image, thresh, log): mask = createMask(image, thresh) log.log(mask) h = cv.CreateImage(cv.GetSize(image), image.depth, 1) cv.CvtColor(image, image, cv.CV_BGR2HSV) cv.Split(image, h, None, None, None) log.log(h) cv.Set(h, cv.ScalarAll(255), mask) return h
def update_high_color(self, pos): self.busy_updating = True self.high_color = pos cv.NamedWindow("End at color", cv.CV_WINDOW_AUTOSIZE) cv.MoveWindow("End at color", 750, 0) color_swatch = cv.CreateImage((200, 140), 8, 3) cv.Set(color_swatch, HSV_to_RGB(self.high_color)) cv.ShowImage("End at color", color_swatch) self.busy_updating = False
def test_2686307(self): lena = cv.LoadImage(find_sample("lena.jpg"), 1) dst = cv.CreateImage((512, 512), 8, 3) cv.Set(dst, (128, 192, 255)) mask = cv.CreateImage((512, 512), 8, 1) cv.Zero(mask) cv.Rectangle(mask, (10, 10), (300, 100), 255, -1) cv.Copy(lena, dst, mask) self.snapL([lena, dst, mask])