Python cv2.cv.ShowImage() Examples

The following are 19 code examples of cv2.cv.ShowImage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2.cv , or try the search function .
Example #1
Source File: distrans.py    From PyCV-time with MIT License 6 votes vote down vote up
def on_trackbar(edge_thresh):

    cv.Threshold(gray, edge, float(edge_thresh), float(edge_thresh), cv.CV_THRESH_BINARY)
    #Distance transform
    cv.DistTransform(edge, dist, cv.CV_DIST_L2, cv.CV_DIST_MASK_5)

    cv.ConvertScale(dist, dist, 5000.0, 0)
    cv.Pow(dist, dist, 0.5)

    cv.ConvertScale(dist, dist32s, 1.0, 0.5)
    cv.AndS(dist32s, cv.ScalarAll(255), dist32s, None)
    cv.ConvertScale(dist32s, dist8u1, 1, 0)
    cv.ConvertScale(dist32s, dist32s, -1, 0)
    cv.AddS(dist32s, cv.ScalarAll(255), dist32s, None)
    cv.ConvertScale(dist32s, dist8u2, 1, 0)
    cv.Merge(dist8u1, dist8u2, dist8u2, None, dist8u)
    cv.ShowImage(wndname, dist8u) 
Example #2
Source File: edge.py    From PyCV-time with MIT License 6 votes vote down vote up
def on_trackbar(position):

    cv.Smooth(gray, edge, cv.CV_BLUR, 3, 3, 0)
    cv.Not(gray, edge)

    # run the edge dector on gray scale
    cv.Canny(gray, edge, position, position * 3, 3)

    # reset
    cv.SetZero(col_edge)

    # copy edge points
    cv.Copy(im, col_edge, edge)

    # show the im
    cv.ShowImage(win_name, col_edge) 
Example #3
Source File: cv20squares.py    From PyCV-time with MIT License 6 votes vote down vote up
def main():
    """Open test color images, create display window, start the search"""
    cv.NamedWindow(WNDNAME, 1)
    for name in [ "../c/pic%d.png" % i for i in [1, 2, 3, 4, 5, 6] ]:
        img0 = cv.LoadImage(name, 1)
        try:
            img0
        except ValueError:
            print "Couldn't load %s\n" % name
            continue

        # slider deleted from C version, same here and use fixed Canny param=50
        img = cv.CloneImage(img0)

        cv.ShowImage(WNDNAME, img)

        # force the image processing
        draw_squares( img, find_squares4( img ) )

        # wait for key.
        if cv.WaitKey(-1) % 0x100 == 27:
            break 
Example #4
Source File: squares.py    From PyCV-time with MIT License 6 votes vote down vote up
def drawSquares(img, squares):
    cpy = cv.CloneImage(img)
    # read 4 sequence elements at a time (all vertices of a square)
    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.PolyLine(cpy, [pt], 1, cv.CV_RGB(0, 255, 0), 3, cv. CV_AA, 0)
        i+=4

    # show the resultant image
    cv.ShowImage(wndname, cpy) 
Example #5
Source File: motion-detection.py    From rpi-opencv with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        started = time.time()
        while True:
            
            currentframe = cv.QueryFrame(self.capture)
            instant = time.time() #Get timestamp o the frame
            
            self.processImage(currentframe) #Process the image
            
            if not self.isRecording:
                if self.somethingHasMoved():
                    self.trigger_time = instant #Update the trigger_time
                    if instant > started +10:#Wait 5 second after the webcam start for luminosity adjusting etc..
                        print "Something is moving !"
                        if self.doRecord: #set isRecording=True only if we record a video
                            self.isRecording = True
                cv.DrawContours (currentframe, self.currentcontours, (0, 0, 255), (0, 255, 0), 1, 2, cv.CV_FILLED)
            else:
                if instant >= self.trigger_time +10: #Record during 10 seconds
                    print "Stop recording"
                    self.isRecording = False
                else:
                    cv.PutText(currentframe,datetime.now().strftime("%b %d, %H:%M:%S"), (25,30),self.font, 0) #Put date on the frame
                    cv.WriteFrame(self.writer, currentframe) #Write the frame
            
            if self.show:
                cv.ShowImage("Image", currentframe)
                
            c=cv.WaitKey(1) % 0x100
            if c==27 or c == 10: #Break if user enters 'Esc'.
                break 
Example #6
Source File: contours.py    From PyCV-time with MIT License 5 votes vote down vote up
def on_trackbar (position):

    # create the image for putting in it the founded contours
    contours_image = cv.CreateImage ( (_SIZE, _SIZE), 8, 3)

    # compute the real level of display, given the current position
    levels = position - 3

    # initialisation
    _contours = contours

    if levels <= 0:
        # zero or negative value
        # => get to the nearest face to make it look more funny
        _contours = contours.h_next().h_next().h_next()

    # first, clear the image where we will draw contours
    cv.SetZero (contours_image)

    # draw contours in red and green
    cv.DrawContours (contours_image, _contours,
                       _red, _green,
                       levels, 3, cv.CV_AA,
                        (0, 0))

    # finally, show the image
    cv.ShowImage ("contours", contours_image) 
Example #7
Source File: demhist.py    From PyCV-time with MIT License 5 votes vote down vote up
def update_brightcont(self):
        # The algorithm is by Werner D. Streidt
        # (http://visca.com/ffactory/archives/5-99/msg00021.html)

        if self.contrast > 0:
            delta = 127. * self.contrast / 100
            a = 255. / (255. - delta * 2)
            b = a * (self.brightness - delta)
        else:
            delta = -128. * self.contrast / 100
            a = (256. - delta * 2) / 255.
            b = a * self.brightness + delta

        cv.ConvertScale(self.src_image, self.dst_image, a, b)
        cv.ShowImage("image", self.dst_image)

        cv.CalcArrHist([self.dst_image], self.hist)
        (min_value, max_value, _, _) = cv.GetMinMaxHistValue(self.hist)
        cv.Scale(self.hist.bins, self.hist.bins, float(self.hist_image.height) / max_value, 0)

        cv.Set(self.hist_image, cv.ScalarAll(255))
        bin_w = round(float(self.hist_image.width) / hist_size)

        for i in range(hist_size):
            cv.Rectangle(self.hist_image, (int(i * bin_w), self.hist_image.height),
                         (int((i + 1) * bin_w), self.hist_image.height - cv.Round(self.hist.bins[i])),
                         cv.ScalarAll(0), -1, 8, 0)

        cv.ShowImage("histogram", self.hist_image) 
Example #8
Source File: morphology.py    From PyCV-time with MIT License 5 votes vote down vote up
def Dilation(pos):
    element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, element_shape)
    cv.Dilate(src, dest, element, 1)
    cv.ShowImage("Erosion & Dilation", dest) 
Example #9
Source File: morphology.py    From PyCV-time with MIT License 5 votes vote down vote up
def Erosion(pos):
    element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, element_shape)
    cv.Erode(src, dest, element, 1)
    cv.ShowImage("Erosion & Dilation", dest) 
Example #10
Source File: morphology.py    From PyCV-time with MIT License 5 votes vote down vote up
def Closing(pos):
    element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, element_shape)
    cv.Dilate(src, image, element, 1)
    cv.Erode(image, dest, element, 1)
    cv.ShowImage("Opening & Closing", dest) 
Example #11
Source File: cv20squares.py    From PyCV-time with MIT License 5 votes vote down vote up
def draw_squares( color_img, squares ):
    """
    Squares is py list containing 4-pt numpy arrays. Step through the list
    and draw a polygon for each 4-group
    """
    color, othercolor = RED, GREEN
    for square in squares:
        cv.PolyLine(color_img, [square], True, color, 3, cv.CV_AA, 0)
        color, othercolor = othercolor, color

    cv.ShowImage(WNDNAME, color_img) 
Example #12
Source File: watershed.py    From PyCV-time with MIT License 5 votes vote down vote up
def on_mouse(self, event, x, y, flags, param):
        pt = (x, y)
        if event == cv.CV_EVENT_LBUTTONUP or not (flags & cv.CV_EVENT_FLAG_LBUTTON):
            self.prev_pt = None
        elif event == cv.CV_EVENT_LBUTTONDOWN:
            self.prev_pt = pt
        elif event == cv.CV_EVENT_MOUSEMOVE and (flags & cv.CV_EVENT_FLAG_LBUTTON) :
            if self.prev_pt:
                for dst in self.dests:
                    cv.Line(dst, self.prev_pt, pt, cv.ScalarAll(255), 5, 8, 0)
            self.prev_pt = pt
            cv.ShowImage(self.windowname, img) 
Example #13
Source File: facedetect.py    From PyCV-time with MIT License 5 votes vote down vote up
def detect_and_draw(img, cascade):
    # allocate temporary images
    gray = cv.CreateImage((img.width,img.height), 8, 1)
    small_img = cv.CreateImage((cv.Round(img.width / image_scale),
                   cv.Round (img.height / image_scale)), 8, 1)

    # convert color input image to grayscale
    cv.CvtColor(img, gray, cv.CV_BGR2GRAY)

    # scale input image for faster processing
    cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)

    cv.EqualizeHist(small_img, small_img)

    if(cascade):
        t = cv.GetTickCount()
        faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0),
                                     haar_scale, min_neighbors, haar_flags, min_size)
        t = cv.GetTickCount() - t
        print "detection time = %gms" % (t/(cv.GetTickFrequency()*1000.))
        if faces:
            for ((x, y, w, h), n) in faces:
                # the input to cv.HaarDetectObjects was resized, so scale the
                # bounding box of each face and convert it to two CvPoints
                pt1 = (int(x * image_scale), int(y * image_scale))
                pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
                cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0)

    cv.ShowImage("result", img) 
Example #14
Source File: pyramid_segmentation.py    From PyCV-time with MIT License 5 votes vote down vote up
def on_segment(self):
        comp = cv.PyrSegmentation(self.image0, self.image1, self.storage, \
                            self.level, self.thresh1+1, self.thresh2+1)
        cv.ShowImage("Segmentation", self.image1) 
Example #15
Source File: pyramid_segmentation.py    From PyCV-time with MIT License 5 votes vote down vote up
def __init__(self, img0):
        self.thresh1 = 255
        self.thresh2 = 30
        self.level =4
        self.storage = cv.CreateMemStorage()
        cv.NamedWindow("Source", 0)
        cv.ShowImage("Source", img0)
        cv.NamedWindow("Segmentation", 0)
        cv.CreateTrackbar("Thresh1", "Segmentation", self.thresh1, 255, self.set_thresh1)
        cv.CreateTrackbar("Thresh2", "Segmentation",  self.thresh2, 255, self.set_thresh2)
        self.image0 = cv.CloneImage(img0)
        self.image1 = cv.CloneImage(img0)
        cv.ShowImage("Segmentation", self.image1) 
Example #16
Source File: handlers.py    From tcg-ocr-scanner with GNU General Public License v3.0 5 votes vote down vote up
def image_captured(self, args):
		(img, rect) = args
		(x, y, w, h) = rect

		cv2.rectangle(numpy.asarray(img[:,:]), (x,y+1), (x+w,y+1+h), (0, 0, 0))
		cv2.rectangle(numpy.asarray(img[:,:]), (x,y), (x+w,y+h), (50, 50, 250))
		
		#cv.PutText(img, message, (0,y+1+2*h), font, (255, 255, 255))
		#cv.PutText(img, message, (0,y+2*h), font, (0, 0, 0))
		#cv.ShowImage('Capture Feedback', cv2.fromarray(img[:,:]))
		cv.ShowImage('Capture Feedback', img) 
Example #17
Source File: fitellipse.py    From PyCV-time with MIT License 4 votes vote down vote up
def process_image(self, slider_pos):
        """
        This function finds contours, draws them and their approximation by ellipses.
        """
        stor = cv.CreateMemStorage()

        # Create the destination images
        image02 = cv.CloneImage(self.source_image)
        cv.Zero(image02)
        image04 = cv.CreateImage(cv.GetSize(self.source_image), cv.IPL_DEPTH_8U, 3)
        cv.Zero(image04)

        # Threshold the source image. This needful for cv.FindContours().
        cv.Threshold(self.source_image, image02, slider_pos, 255, cv.CV_THRESH_BINARY)

        # Find all contours.
        cont = cv.FindContours(image02,
            stor,
            cv.CV_RETR_LIST,
            cv.CV_CHAIN_APPROX_NONE,
            (0, 0))

        for c in contour_iterator(cont):
            # Number of points must be more than or equal to 6 for cv.FitEllipse2
            if len(c) >= 6:
                # Copy the contour into an array of (x,y)s
                PointArray2D32f = cv.CreateMat(1, len(c), cv.CV_32FC2)
                for (i, (x, y)) in enumerate(c):
                    PointArray2D32f[0, i] = (x, y)

                # Draw the current contour in gray
                gray = cv.CV_RGB(100, 100, 100)
                cv.DrawContours(image04, c, gray, gray,0,1,8,(0,0))

                # Fits ellipse to current contour.
                (center, size, angle) = cv.FitEllipse2(PointArray2D32f)

                # Convert ellipse data from float to integer representation.
                center = (cv.Round(center[0]), cv.Round(center[1]))
                size = (cv.Round(size[0] * 0.5), cv.Round(size[1] * 0.5))

                # Draw ellipse in random color
                color = cv.CV_RGB(random.randrange(256),random.randrange(256),random.randrange(256))
                cv.Ellipse(image04, center, size,
                          angle, 0, 360,
                          color, 2, cv.CV_AA, 0)

        # Show image. HighGUI use.
        cv.ShowImage( "Result", image04 ) 
Example #18
Source File: ffilldemo.py    From PyCV-time with MIT License 4 votes vote down vote up
def on_mouse( event, x, y, flags, param ):

    if( not color_img ):
        return;

    if event == cv.CV_EVENT_LBUTTONDOWN:
            my_mask = None
            seed = (x,y);
            if ffill_case==0:
                lo = up = 0
                flags = connectivity + (new_mask_val << 8)
            else:
                lo = lo_diff;
                up = up_diff;
                flags = connectivity + (new_mask_val << 8) + cv.CV_FLOODFILL_FIXED_RANGE
            b = random.randint(0,255)
            g = random.randint(0,255)
            r = random.randint(0,255)

            if( is_mask ):
                my_mask = mask
                cv.Threshold( mask, mask, 1, 128, cv.CV_THRESH_BINARY );

            if( is_color ):

                color = cv.CV_RGB( r, g, b );
                comp = cv.FloodFill( color_img, seed, color, cv.CV_RGB( lo, lo, lo ),
                             cv.CV_RGB( up, up, up ), flags, my_mask );
                cv.ShowImage( "image", color_img );

            else:

                brightness = cv.RealScalar((r*2 + g*7 + b + 5)/10);
                comp = cv.FloodFill( gray_img, seed, brightness, cv.RealScalar(lo),
                             cv.RealScalar(up), flags, my_mask );
                cv.ShowImage( "image", gray_img );


            print "%g pixels were repainted" % comp[0]

            if( is_mask ):
                cv.ShowImage( "mask", mask ); 
Example #19
Source File: camshift.py    From PyCV-time with MIT License 4 votes vote down vote up
def run(self):
        hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0,180)], 1 )
        backproject_mode = False
        while True:
            frame = cv.QueryFrame( self.capture )

            # Convert to HSV and keep the hue
            hsv = cv.CreateImage(cv.GetSize(frame), 8, 3)
            cv.CvtColor(frame, hsv, cv.CV_BGR2HSV)
            self.hue = cv.CreateImage(cv.GetSize(frame), 8, 1)
            cv.Split(hsv, self.hue, None, None, None)

            # Compute back projection
            backproject = cv.CreateImage(cv.GetSize(frame), 8, 1)

            # Run the cam-shift
            cv.CalcArrBackProject( [self.hue], backproject, hist )
            if self.track_window and is_rect_nonzero(self.track_window):
                crit = ( cv.CV_TERMCRIT_EPS | cv.CV_TERMCRIT_ITER, 10, 1)
                (iters, (area, value, rect), track_box) = cv.CamShift(backproject, self.track_window, crit)
                self.track_window = rect

            # If mouse is pressed, highlight the current selected rectangle
            # and recompute the histogram

            if self.drag_start and is_rect_nonzero(self.selection):
                sub = cv.GetSubRect(frame, self.selection)
                save = cv.CloneMat(sub)
                cv.ConvertScale(frame, frame, 0.5)
                cv.Copy(save, sub)
                x,y,w,h = self.selection
                cv.Rectangle(frame, (x,y), (x+w,y+h), (255,255,255))

                sel = cv.GetSubRect(self.hue, self.selection )
                cv.CalcArrHist( [sel], hist, 0)
                (_, max_val, _, _) = cv.GetMinMaxHistValue( hist)
                if max_val != 0:
                    cv.ConvertScale(hist.bins, hist.bins, 255. / max_val)
            elif self.track_window and is_rect_nonzero(self.track_window):
                cv.EllipseBox( frame, track_box, cv.CV_RGB(255,0,0), 3, cv.CV_AA, 0 )

            if not backproject_mode:
                cv.ShowImage( "CamShiftDemo", frame )
            else:
                cv.ShowImage( "CamShiftDemo", backproject)
            cv.ShowImage( "Histogram", self.hue_histogram_as_image(hist))

            c = cv.WaitKey(7) % 0x100
            if c == 27:
                break
            elif c == ord("b"):
                backproject_mode = not backproject_mode