예제 #1
0
 def draw(self, mousePos=None):
     '''
     Computes the image montage from the source images based on the current
     image pointer (position in list of images), etc. This internally constructs
     the montage, but show() is required for display and mouse-click handling.
     '''
     cv.SetZero(self._cvMontageImage)
     
     img_ptr = self._imgPtr
     if img_ptr > 0:
         #we are not showing the first few images in imageList
         #so display the decrement arrow
         cv.FillConvexPoly(self._cvMontageImage, self._decrArrow, (125,125,125))
         
     if img_ptr + (self._rows*self._cols) < len(self._images):
         #we are not showing the last images in imageList
         #so display increment arrow
         cv.FillConvexPoly(self._cvMontageImage, self._incrArrow, (125,125,125))
     
     
     if self._byrow:
         for row in range(self._rows):
             for col in range(self._cols):
                 if img_ptr > len(self._images)-1: break
                 tile = pv.Image(self._images[img_ptr].asAnnotated())
                 self._composite(tile, (row,col), img_ptr)
                 img_ptr += 1
     else:
         for col in range(self._cols):
             for row in range(self._rows):
                 if img_ptr > len(self._images)-1: break
                 tile = pv.Image(self._images[img_ptr].asAnnotated())
                 self._composite(tile, (row,col), img_ptr)
                 img_ptr += 1
예제 #2
0
def plot_color_rectangle(image, mask):
    a = screen_height
    width = 180
    height = 256
    #print (width, height)
    color_rectangle = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 3)
    (image_width, image_height) = cv.GetSize(cv.fromarray(image))
    #print (image_width, image_height)
    rectangle = (((0, 0), (width, 0), (width, height), (0, height)), BLACK)
    cv.FillConvexPoly(color_rectangle, *rectangle)
    converted_image = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)
    for i in range(image_height):
        for j in range(image_width):
            if mask == None or mask[i][j]:
                color = image[i][j]
                hls = converted_image[i][j]
                #print color
                (h, l, s) = hls
                hls = (h, l, s)
                #print hls
                x = int(h)
                y = int(l)
                color = cv.Scalar(*color)
                rectangle = (((x, y), (x, y), (x, y), (x, y)), color)
                cv.FillConvexPoly(color_rectangle, *rectangle)
    #x = (a - 1) / 2
    #y = (a - 1) / 2
    #white_dot = (x, y)
    #rectangle = ((white_dot, white_dot, white_dot, white_dot), WHITE)
    cv.FillConvexPoly(color_rectangle, *rectangle)
    return color_rectangle
예제 #3
0
 def paint_cameras(self, img):
     "paints the cameras onto the image"
     (co,cw,cs) = (10,30,60)
     (w,h) = kc.img_size
     coords = [self.cam1center, (cs,cw), (cw, cs)]
     cv.FillConvexPoly(img, coords, kc.cam1color)
     coords = [self.cam2center, (w-cs,cw), (w-cw, cs)]
     cv.FillConvexPoly(img, coords, kc.cam2color)
예제 #4
0
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));
예제 #5
0
    def draw(self, vis):
        self.adjustCamera()
        for i in xrange(len(self.colors)):
            (center, norm, up, right) = self.faceInfo(i)
            if norm**(center - self.camera.pos) < 0:
                corners = (center + up * 0.5 + right * 0.5,
                           center + up * 0.5 - right * 0.5,
                           center - up * 0.5 - right * 0.5,
                           center - up * 0.5 + right * 0.5)
                corners = [corner.flatten(self.camera) for corner in corners]
                corners = [(int(corner[0]), int(corner[1]))
                           for corner in corners]
                cv.FillConvexPoly(cv.fromarray(vis),
                                  corners,
                                  colorTuple(self.colors[i]),
                                  lineType=4,
                                  shift=0)

        for i in xrange(len(self.colors)):
            (center, norm, up, right) = self.faceInfo(i)
            if norm**(center - self.camera.pos) < 0:
                corners = (center + up * 0.5 + right * 0.5,
                           center + up * 0.5 - right * 0.5,
                           center - up * 0.5 - right * 0.5,
                           center - up * 0.5 + right * 0.5)
                corners = [corner.flatten(self.camera) for corner in corners]
                corners = [(int(corner[0]), int(corner[1]))
                           for corner in corners]

                for j in xrange(len(corners)):
                    k = (j + 1) % (len(corners))
                    cv.Line(cv.fromarray(vis), corners[j], corners[k],
                            (0, 0, 0))
예제 #6
0
def draw_it(scores, width=500, height=500, radiu=200, filename='result.png'):
    image = cv.CreateImage((width, height), 8, 3)

    text = ["O", "C", "E", "A", "N"]

    # background color
    cv.Rectangle(image, (0, 0), (width, height), (0x9C, 0x90, 0x92), -1)

    # center and angle
    cx = width * 0.5
    cy = height * 0.5
    angle = math.pi * 0.4

    # draw outer pentagon
    pt = []
    for i in range(0, 5):
        pt.append((int(cx + radiu * math.sin(angle * i)),
                   int(cy - radiu * math.cos(angle * i))))
    cv.FillConvexPoly(image, pt, (0xDC, 0xC0, 0xB2))

    # draw inner polygon
    pt = []
    for i, t in enumerate(text):
        pt.append((int(cx + scores[t] * radiu * math.sin(angle * i)),
                   int(cy - scores[t] * radiu * math.cos(angle * i))))
    cv.FillConvexPoly(image, pt, (0xAC, 0x80, 0x82))

    # draw lines
    colors = [(0x33, 0x33, 0xFF), (0x33, 0xFF, 0xFF), (0x33, 0xEF, 0x66),
              (0xCC, 0x66, 0x00), (0xCC, 0x00, 0x66)]
    for i in range(0, 5):
        cv.Line(image, (int(cx), int(cy)),
                (int(cx + radiu * math.sin(angle * i)),
                 int(cy - radiu * math.cos(angle * i))), colors[i], 2)

    # draw text
    font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8)
    for i, t in enumerate(text):
        cv.PutText(image, t,
                   (int(cx + (radiu + 20) * math.sin(angle * i)) - 10,
                    int(cy - (radiu + 20) * math.cos(angle * i)) + 10), font,
                   (0, 0, 0))

    cv.SaveImage(filename, image)
예제 #7
0
def plot_color_triangle(image, mask):
    a = screen_height
    height = a
    width = int(math.ceil(2 * a / math.sqrt(3)))
    #print (width, height)
    color_triangle = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 3)
    (image_width, image_height) = cv.GetSize(cv.fromarray(image))
    #print (image_width, image_height)
    rectangle = (((0, 0), (width, 0), (width, height), (0, height)), BLACK)
    cv.FillConvexPoly(color_triangle, *rectangle)
    for i in range(image_height):
        for j in range(image_width):
            if mask == None or mask[i][j]:
                color = image[i][j]
                #print color
                (B, G, R) = color
                color = (B, G, R)
                #print color
                intensity = float(sum(color))
                if intensity == 0:
                    b = 1.0 / 3.0
                    g = 1.0 / 3.0
                else:
                    b = (B / intensity)
                    g = (G / intensity)
                #print b, g
                x = math.sqrt(3) * (a - 1) * (1 - b) / 2
                y = (a - 1) * (1 - g)
                x = int(x)
                y = int(y)
                #print x, y
                #print color_triangle[0][0]
                #color_triangle[x][y] = 255
                color = cv.Scalar(*color)
                rectangle = (((x, y), (x, y), (x, y), (x, y)), color)
                cv.FillConvexPoly(color_triangle, *rectangle)
    x = (a - 1) / math.sqrt(3)
    y = 2 * (a - 1) / 3.0
    white_dot = (x, y)
    rectangle = ((white_dot, white_dot, white_dot, white_dot), WHITE)
    cv.FillConvexPoly(color_triangle, *rectangle)
    return color_triangle
예제 #8
0
def plot_heatmap(similarity_matrix, n):
    if n != 0:
        pixels = max(1, min(screen_width / n, screen_height / n))
        side = n * pixels
        heatmap = cv.CreateImage((side, side), cv.IPL_DEPTH_8U, 1)
        for i in range(n):
            for j in range(n):
                (a, b) = (i * pixels, j * pixels)
                (c, d) = (a + pixels, b + pixels)
                intensity = int((1 - similarity_matrix[(i, j)]) * 255)
                rectangle = (((a, b), (c, b), (c, d), (a, d)), intensity)
                cv.FillConvexPoly(heatmap, *rectangle)
        cv.ShowImage('heatmap', heatmap)
예제 #9
0
    def channel_to_image(self, chan, scale_x=3, scale_y=3, y_range=64):
        """
        Creates an iplimage displaying histogram results after its computation
        """
        if ((type(chan) != int) or (chan <= 0)):
            raise TypeError("(%s) Positive integer expected!" %
                            (sys._getframe().f_code.co_name))
        elif chan > self.channels:
            raise ValueError("(%s) Incoherent channel selected!" %
                             (sys._getframe().f_code.co_name))

        if ((type(scale_x) != int) or (scale_x <= 0)):
            raise TypeError("(%s) Positive integer expected!" %
                            (sys._getframe().f_code.co_name))

        if ((type(scale_y) != int) or (scale_y <= 0)):
            raise TypeError("(%s) Positive integer expected!" %
                            (sys._getframe().f_code.co_name))

        if ((type(y_range) != int) or (y_range <= 0)):
            raise TypeError("(%s) Positive integer expected!" %
                            (sys._getframe().f_code.co_name))

        max_range = self.ranges[1] - 1
        (_, hist_max, _, _) = cv.GetMinMaxHistValue(self.cvhist[chan - 1])
        hist_img = cv.CreateImage((max_range * scale_x, y_range * scale_y),
                                  self.depth, 1)
        cv.Zero(hist_img)  # resets image values

        for i in range(max_range):  # 0 to max_range
            hist_value = cv.QueryHistValue_1D(self.cvhist[chan - 1], i)
            next_value = cv.QueryHistValue_1D(self.cvhist[chan - 1], i + 1)
            pt1 = (int(i * scale_x), int(y_range * scale_y))
            pt2 = (int(i * scale_x + scale_x), int(y_range * scale_y))
            pt3 = (int(i * scale_x + scale_x),
                   int((y_range - (next_value * y_range / hist_max)) *
                       scale_y))
            pt4 = (int(i * scale_x),
                   int((y_range - (hist_value * y_range / hist_max)) *
                       scale_y))
            pts = (pt1, pt2, pt3, pt4)
            cv.FillConvexPoly(hist_img, pts, 255, lineType=8, shift=0)

        return hist_img
예제 #10
0
 def _test_improve_corners(self, a, b):
     cv.FillConvexPoly(self.draw_img, self.points, (255, 255, 255))
    # cv.Circle(self.draw_img, (75,30), 20, (0,0,0),4)
     ncorners = self._prepare_corners(self.points)
     CP = CornerPredictor(self.corners, 1, self.draw_img, self.timg,self.tmp_img)
     ncorners[a] = None
     ncorners[b] = None
     corners = CP._improve_corners(ncorners)
     for i in filter(lambda x: (x <> a and x <> b), range(4)):
         ea = r2d(self.corners[i].angle)
         print '-----',ncorners[i].prev,ncorners[i].p, ncorners[i].next, corners[i].prev, corners[i].next 
         na = r2d(ncorners[i].angle)
         ra = r2d(corners[i].angle)
         self.assertTrue(abs(ea - ra) <= abs(ea-na), 'Angle of [%d] not improved: \
                                     expected %f received %f previous %f' % (i, ea, ra, na))
         ea = r2d(self.corners[i].rotation)
         na = r2d(ncorners[i].rotation)
         ra = r2d(corners[i].rotation)
         self.assertTrue(abs(ea - ra) <= abs(ea-na) , 'rotation of [%d] not improved: \
                                     expected %f received %f previous %f' % (i, ea, ra, na))                            
예제 #11
0
 def _predict(self,npoints):
     cv.FillConvexPoly(self.draw_img, npoints, (0,0,0))
     corners = Corner.get_corners(npoints)
     tcorners = list(corners)
     for i,cor in enumerate(corners):
         print cor.p
         if not(0<=cor.p[0]<self.size and 0<=cor.p[1]<self.size):
             tcorners[i]=None
     
     CP = CornerPredictor(self.corners, 1, self.tmp_img, self.timg, self.draw_img)
     print "predicting....",tcorners
     ncorners = CP.predict_corners(tcorners)
     print 'done'
     for i,cor in enumerate(ncorners):
         v=vector(corners[i].p,cor.p)
         print length(v), cor.toString()
         self.assertTrue(length(v)<5,"Wrong prediction!Corner: %d \
         Expected: (%d,%d) received (%d,%d)" \
         %(i,corners[i].p[0],corners[i].p[1],cor.p[0],cor.p[1]))
     print ncorners  
예제 #12
0
            last = corners[-1]
            new_corners[last.id] = None
            self.avg_sim = self.avg_sim * len(corners) - last.similarity
            corners.remove(last)

        return None



if __name__ == '__main__':
    img = cv.CreateImage((100, 100), 8, 1)
    a = (50, -10)
    b = (85, 50)
    c = (50, 90)
    d = (5, 50)
    cv.FillConvexPoly(img, [a, b, c, d], (255, 255, 255))
    temp = 'temp'
    cv.NamedWindow(temp)

    oa, ob, oc, od = (48, -8), (80, 50), (48, 88), (0, 50)
    points = [oa, ob, oc, od]
    corners = [Corner(points, 0), Corner(points, 1), Corner(points, 2), Corner(points, 3)]
    CP = CornerPredictor(corners, 50, img)

    cv.PolyLine(img, [[oa, ob, oc, od]], 1, (150, 100, 100))

    dimg = cv.CreateImage((200, 200), 8, 1)
    cv.PyrUp(img, dimg)
    cv.ShowImage(temp, dimg)
    cv.WaitKey(10000)
예제 #13
0
    def detect(self, img, ConvexHulls=False):
        '''
        You call this method to update detection results, given the new
        image in the stream. After updating detection results, use one
        of the get*() methods, such as getRects() to see the results in the
        appropriate format.
        
        @param img: A pv.Image() to be added to the buffer as the most recent image,
        and that triggers the new motion detection. Note that, depending on the
        background subtraction method, this may not be the "key frame" for the 
        detection. The Frame Differencer returns a background model based on the
        middle image, but Median and Approx. Median Filters return a background
        model based on the most recent (last) image in the buffer. 
        
        @param ConvexHulls: If true, then the detected foreground pixels are
        grouped into convex hulls, which can have the effect of removing internal
        "holes" in the detection.
        
        @return: The number of detected components in the current image. To get
        more details, use the various getX() methods, like getForegroundMask(),
        after calling detect().
        
        @note: Until the image buffer is full, this method will make no detections.
        In which case, the return value will be -1, indicating this status. Also,
        the getKeyFrame() method should be used to retrieve the key frame from
        the buffer, which is not always the most recent image, depending on background
        subtraction method.
        '''
        # Smooth the image
        cvim = img.asOpenCV()
        cvim = cv.CloneImage(cvim)
        if self._smooth:
            cv.Smooth(cvim, cvim)

        self._imageBuff.add(pv.Image(cvim))
        if not self._imageBuff.isFull():
            return -1

        #initialize background subtraction object only after buffer is full.
        if self._bgSubtract == None:
            self._initBGSubtract()

        #update current annotation image from buffer, as appropriate for
        # the different methods
        if self._method == BG_SUBTRACT_FD:
            self._annotateImg = self._imageBuff.getMiddle()
        if self._method == BG_SUBTRACT_MCFD:
            self._annotateImg = self._imageBuff.getMiddle()
        elif self._method == BG_SUBTRACT_MF:
            self._annotateImg = self._imageBuff.getLast()
        elif self._method == BG_SUBTRACT_AMF:
            self._annotateImg = self._imageBuff.getLast()

        mask = self._bgSubtract.getForegroundMask()
        #        if self._softThreshold:
        #            cvWeights = mask.asOpenCVBW()
        #            scale = (1.0/255.0)  #because weights are 0-255 in mask image
        #            cvCurImg = self._annotateImg.copy().asOpenCVBW()
        #            cvDst = cv.CreateImage(cv.GetSize(cvWeights), cv.IPL_DEPTH_8U, 1)
        #            cv.Mul(cvWeights, cvCurImg, cvDst, scale)
        #            cv.Smooth(cvDst, cvDst)
        #            #update the foreground mask
        #            self._fgMask = pv.Image(cvDst)
        #        else:

        cvBinary = mask.asOpenCVBW()
        cv.Smooth(cvBinary, cvBinary)
        cv.Dilate(cvBinary, cvBinary, None, 3)
        cv.Erode(cvBinary, cvBinary, None, 1)

        #update the foreground mask
        self._fgMask = pv.Image(cvBinary)

        #update the detected foreground contours
        self._computeContours()
        self._computeConvexHulls()

        if ConvexHulls:
            for hull in self._convexHulls:
                cv.FillConvexPoly(cvBinary, hull, cv.RGB(255, 255, 255))
            #k = cv.CreateStructuringElementEx(15, 15, 7, 7, cv.CV_SHAPE_RECT)
            #cv.Dilate(mask, mask, element=k, iterations=1)

        return len(self._contours)
예제 #14
0
파일: main.py 프로젝트: AlexKordic/obj_att
             conts = conts.h_next()
         
         # prepare for search for next hill
         start, end = i, i
         c += 1
         
     x_scale = 1
     # draw current value in histogram
     try:
         pts = [(int(i * x_scale), hist_height),
                (int(i * x_scale + x_scale), hist_height),
                (int(i * x_scale + x_scale), int(hist_height - next_value * hist_height / max_hist)),
                (int(i * x_scale), int(hist_height - cur_value * hist_height / max_hist))]
     except:
         print 'don\'t put your hand in front of the camera !!!'
     cv.FillConvexPoly(hist_img, pts, color_tab[c])
           
 # time the histogram clustering
 timing['t_pre'] += time.time() - t0
 
 # iterate over tracked objects
 sift = False
 for obj in objects:
     found = False
     
     # if sift not done in this frame, object not yet labelled and already seen a few times
     if((obj.frames == None and obj.count > n_sift and sift == False) or
       (obj.frames != None and obj.count % 30 == 0)):
         sift_pool.put((obj, current_image_frame))
         sift = True     # enough work added for this frame
         
예제 #15
0
def visualizePolygons(image, polygons):
    #note that this modifies the passed image!
    for polygonI, polygon in enumerate(polygons):
        polygon = [(int(p[0]), int(p[1])) for p in polygon]
        cv.FillConvexPoly(image, polygon, polygonI + 1, 4)
예제 #16
0
    def test_2542670(self):
        xys = [
            (94, 121), (94, 122), (93, 123), (92, 123), (91, 124), (91, 125),
            (91, 126), (92, 127), (92, 128), (92, 129), (92, 130), (92, 131),
            (91, 132), (90, 131), (90, 130), (90, 131), (91, 132), (92, 133),
            (92, 134), (93, 135), (94, 136), (94, 137), (94, 138), (95, 139),
            (96, 140), (96, 141), (96, 142), (96, 143), (97, 144), (97, 145),
            (98, 146), (99, 146), (100, 146), (101, 146), (102, 146),
            (103, 146), (104, 146), (105, 146), (106, 146), (107, 146),
            (108, 146), (109, 146), (110, 146), (111, 146), (112, 146),
            (113, 146), (114, 146), (115, 146), (116, 146), (117, 146),
            (118, 146), (119, 146), (120, 146), (121, 146), (122, 146),
            (123, 146), (124, 146), (125, 146), (126, 146), (126, 145),
            (126, 144), (126, 143), (126, 142), (126, 141), (126, 140),
            (127, 139), (127, 138), (127, 137), (127, 136), (127, 135),
            (127, 134), (127, 133), (128, 132), (129, 132), (130, 131),
            (131, 130), (131, 129), (131, 128), (132, 127), (133, 126),
            (134, 125), (134, 124), (135, 123), (136, 122), (136, 121),
            (135, 121), (134, 121), (133, 121), (132, 121), (131, 121),
            (130, 121), (129, 121), (128, 121), (127, 121), (126, 121),
            (125, 121), (124, 121), (123, 121), (122, 121), (121, 121),
            (120, 121), (119, 121), (118, 121), (117, 121), (116, 121),
            (115, 121), (114, 121), (113, 121), (112, 121), (111, 121),
            (110, 121), (109, 121), (108, 121), (107, 121), (106, 121),
            (105, 121), (104, 121), (103, 121), (102, 121), (101, 121),
            (100, 121), (99, 121), (98, 121), (97, 121), (96, 121), (95, 121)
        ]

        #xys = xys[:12] + xys[16:]
        pts = cv.CreateMat(len(xys), 1, cv.CV_32SC2)
        for i, (x, y) in enumerate(xys):
            pts[i, 0] = (x, y)
        storage = cv.CreateMemStorage()
        hull = cv.ConvexHull2(pts, storage)
        hullp = cv.ConvexHull2(pts, storage, return_points=1)
        defects = cv.ConvexityDefects(pts, hull, storage)

        vis = cv.CreateImage((1000, 1000), 8, 3)
        x0 = min([x for (x, y) in xys]) - 10
        x1 = max([x for (x, y) in xys]) + 10
        y0 = min([y for (y, y) in xys]) - 10
        y1 = max([y for (y, y) in xys]) + 10

        def xform(pt):
            x, y = pt
            return (1000 * (x - x0) / (x1 - x0), 1000 * (y - y0) / (y1 - y0))

        for d in defects[:2]:
            cv.Zero(vis)

            # First draw the defect as a red triangle
            cv.FillConvexPoly(vis, [xform(p) for p in d[:3]],
                              cv.RGB(255, 0, 0))

            # Draw the convex hull as a thick green line
            for a, b in zip(hullp, hullp[1:]):
                cv.Line(vis, xform(a), xform(b), cv.RGB(0, 128, 0), 3)

            # Draw the original contour as a white line
            for a, b in zip(xys, xys[1:]):
                cv.Line(vis, xform(a), xform(b), (255, 255, 255))

            self.snap(vis)