Esempio n. 1
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cv2.cv as cv
import cv2
import numpy
import socket

UBU_HOST_NAME = 'gaubutwo.local'  #ラズパイUDP受信ホスト名
UBU_HOST_PORT = 4001  #ラズパイUDP受信ポート番号
if __name__ == "__main__":
    cv.NamedWindow("serverCAM", 1)  #表示するウィンドウ作成
    udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp.bind(('gaubutwo.local', 4001))
    buff = 1024
    while True:
        jpgstring, addr = udp.recvfrom(buff *
                                       64)  #送られてくるデータが大きいので一度に受け取るデータ量を大きく設定
        narray = numpy.fromstring(jpgstring,
                                  dtype="uint8")  #string型からnumpyを用いuint8に戻す
        decimg = cv2.imdecode(narray, 1)  #uint8のデータを画像データに戻す
        cv2.imshow("serverCAM", decimg)  #画像の表示
        if cv.WaitKey(10) == 27:
            break
    cv.DestroyAllWindows()
    udp.close()
Esempio n. 2
0
    print "\tc - switch color/grayscale mode"
    print "\tm - switch mask mode"
    print "\tr - restore the original image"
    print "\ts - use null-range floodfill"
    print "\tf - use gradient floodfill with fixed(absolute) range"
    print "\tg - use gradient floodfill with floating(relative) range"
    print "\t4 - use 4-connectivity mode"
    print "\t8 - use 8-connectivity mode"

    color_img = cv.CloneImage( im );
    gray_img0 = cv.CreateImage( (color_img.width, color_img.height), 8, 1 );
    cv.CvtColor( color_img, gray_img0, cv.CV_BGR2GRAY );
    gray_img = cv.CloneImage( gray_img0 );
    mask = cv.CreateImage( (color_img.width + 2, color_img.height + 2), 8, 1 );

    cv.NamedWindow( "image", 1 );
    cv.CreateTrackbar( "lo_diff", "image", lo_diff, 255, update_lo);
    cv.CreateTrackbar( "up_diff", "image", up_diff, 255, update_up);

    cv.SetMouseCallback( "image", on_mouse );

    while True:
        if( is_color ):
            cv.ShowImage( "image", color_img );
        else:
            cv.ShowImage( "image", gray_img );

        c = cv.WaitKey(0) % 0x100
        if c == 27:
            print("Exiting ...");
            sys.exit(0)
Esempio n. 3
0

if __name__ == '__main__':

    TP = 0
    FP = 0
    TN = 0
    FN = 0

    # Process command line options to determine whether to look at the images
    # and keypoints as they are processed.
    show_images = False
    if len(sys.argv) > 1 and (sys.argv[1] == '--show' or sys.argv[1] == '-s'):
        show_images = True
    if show_images:
        cv.NamedWindow('result', 1)

    # Directories containing test images
    dir_prefix = '../data/'
    test_directories = ['test-positive', 'test-negative']

    for image_directory in test_directories:

        # Read the list of test image files
        source_dir = dir_prefix + image_directory + '/'
        img_files = glob.glob(source_dir + '*.jpg')

        filenumber = 1
        nfiles = len(img_files)
        for testfile in img_files:
            print '%s (%d/%d)' % (testfile, filenumber, nfiles)
Esempio n. 4
0
import cv2.cv as cv
import time
import sys

camid = int(sys.argv[1])
print camid
cv.NamedWindow("camera", camid)

capture = cv.CaptureFromCAM(1)

while True:
    img = cv.QueryFrame(capture)
    cv.ShowImage("camera", img)
    if cv.WaitKey(10) == 27:
        break
import cv2.cv as cv
import cv2
import numpy as np
import math
import visualServo

dd = diff_drive
ref = dd.H_REF()
tim = dd.H_TIME()

ROBOT_DIFF_DRIVE_CHAN = 'robot-diff-drive'
ROBOT_CHAN_VIEW_R = 'robot-vid-chan-r'
ROBOT_CHAN_VIEW_L = 'robot-vid-chan-l'
ROBOT_TIME_CHAN = 'robot-time'
# CV setup
cv.NamedWindow("wctrl_L", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("wctrl_R", cv.CV_WINDOW_AUTOSIZE)
#capture = cv.CaptureFromCAM(0)
#capture = cv2.VideoCapture(0)

# added
##sock.connect((MCAST_GRP, MCAST_PORT))
newx = 320
newy = 240

nx = 320
ny = 240

r = ach.Channel(ROBOT_DIFF_DRIVE_CHAN)
r.flush()
vl = ach.Channel(ROBOT_CHAN_VIEW_L)
Esempio n. 6
0
if __name__ == '__main__':
    if len(sys.argv) > 1:
        im = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR)
    else:
        url = 'http://code.opencv.org/projects/opencv/repository/revisions/master/raw/samples/c/fruits.jpg'
        filedata = urllib2.urlopen(url).read()
        imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
        cv.SetData(imagefiledata, filedata, len(filedata))
        im = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR)

    # create the output im
    col_edge = cv.CreateImage((im.width, im.height), 8, 3)

    # convert to grayscale
    gray = cv.CreateImage((im.width, im.height), 8, 1)
    edge = cv.CreateImage((im.width, im.height), 8, 1)
    cv.CvtColor(im, gray, cv.CV_BGR2GRAY)

    # create the window
    cv.NamedWindow(win_name, cv.CV_WINDOW_AUTOSIZE)

    # create the trackbar
    cv.CreateTrackbar(trackbar_name, win_name, 1, 100, on_trackbar)

    # show the im
    on_trackbar(0)

    # wait a key pressed to end
    cv.WaitKey(0)
    cv.DestroyAllWindows()
Esempio n. 7
0
i = 0

# initialisation des paramètres pour la capture
camera = PiCamera()
camera.resolution = (1920, 1080)
camera.framerate = 32
camera.rotation = 180

# temps réservé pour l'autofocus
time.sleep(0.1)
camera.start_preview()
while True:
    key = cv2.waitKey(1) & 0xFF
    if key == ord("s"):
        camera.stop_preview()
    if key == "c":
        camera.capture('/home/pi/Desktop/image' + str(i) + '.jpg')
        i += 1

import cv2.cv as cv

if __name__ == '__main__':
    ma_caméra = cv.CaptureFromCAM(0)
    cv.NamedWindow("Test_Webcam")
    while True:
        ma_frame = cv.QueryFrame(ma_caméra)
        cv.ShowImage("Test_Webcam", ma_frame)

        if (cv.WaitKey(10) % 0x100) == 113:
            break
Esempio n. 8
0
if __name__ == '__main__':

    # some "constants"
    width = 1000
    height = 700
    window_name = "Drawing Demo"
    number = 100
    delay = 5
    line_type = cv.CV_AA  # change it to 8 to see non-antialiased graphics

    # create the source image
    image = cv.CreateImage((width, height), 8, 3)

    # create window and display the original picture in it
    cv.NamedWindow(window_name, 1)
    cv.SetZero(image)
    cv.ShowImage(window_name, image)

    # create the random number
    random = Random()

    # draw some lines
    for i in range(number):
        pt1 = (random.randrange(-width, 2 * width),
               random.randrange(-height, 2 * height))
        pt2 = (random.randrange(-width, 2 * width),
               random.randrange(-height, 2 * height))
        cv.Line(image, pt1, pt2, random_color(random), random.randrange(0, 10),
                line_type, 0)
Esempio n. 9
0
import cv2.cv as cv
import cv2

image = cv.LoadImage('3.jpg',0)
size = (image.width,image.height)
iTmp = cv.CreateImage(size,image.depth,image.nChannels)
for i in range(image.height):
      for j in range(image.width):
          iTmp[i,j] = 255 - image[i,j]

cv.NamedWindow('image')
cv.NamedWindow('iTmp')
cv.ShowImage('image',image)
cv.ShowImage('iTmp',iTmp)
cv.WaitKey(0)
Esempio n. 10
0
        # Show image. HighGUI use.
        cv.ShowImage("Result", image04)


if __name__ == '__main__':
    if len(sys.argv) > 1:
        source_image = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_GRAYSCALE)
    else:
        url = 'https://raw.github.com/opencv/opencv/master/samples/c/stuff.jpg'
        filedata = urllib2.urlopen(url).read()
        imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
        cv.SetData(imagefiledata, filedata, len(filedata))
        source_image = cv.DecodeImage(imagefiledata,
                                      cv.CV_LOAD_IMAGE_GRAYSCALE)

    # Create windows.
    cv.NamedWindow("Source", 1)
    cv.NamedWindow("Result", 1)

    # Show the image.
    cv.ShowImage("Source", source_image)

    fe = FitEllipse(source_image, 70)

    print "Press any key to exit"
    cv.WaitKey(0)

    cv.DestroyWindow("Source")
    cv.DestroyWindow("Result")
Esempio n. 11
0
    def __init__(self):
        rospy.init_node('avi2ros', anonymous=True)
        
        self.input = rospy.get_param("~input", "")
        self.output = rospy.get_param("~output", "video_output")       
        self.fps = rospy.get_param("~fps", 25)
        self.loop = rospy.get_param("~loop", False)
        self.width = rospy.get_param("~width", "")
        self.height = rospy.get_param("~height", "")
        self.start_paused = rospy.get_param("~start_paused", False)
        self.show_viz = not rospy.get_param("~headless", False)
        self.show_text = True

        image_pub = rospy.Publisher(self.output, Image, queue_size=10)
        
        rospy.on_shutdown(self.cleanup)
        
        video = cv.CaptureFromFile(self.input)
        fps = int(cv.GetCaptureProperty(video, cv.CV_CAP_PROP_FPS))
        
        """ Bring the fps up to the specified rate """
        try:
            fps = int(fps * self.fps / fps)
        except:
            fps = self.fps
    
        if self.show_viz:
            cv.NamedWindow("AVI Video", True) # autosize the display
            cv.MoveWindow("AVI Video", 650, 100)

        bridge = CvBridge()
                
        self.paused = self.start_paused
        self.keystroke = None
        self.restart = False
        
        # Get the first frame to display if we are starting in the paused state.
        frame = cv.QueryFrame(video)
        image_size = cv.GetSize(frame)
        
        if self.width and self.height and (self.width != image_size[0] or self.height != image_size[1]):
            rospy.loginfo("Resizing! " + str(self.width) + " x " + str(self.height))
            resized_frame = cv.CreateImage((self.width, self.height), frame.depth, frame.channels)
            cv.Resize(frame, resized_frame)
            frame = cv.CloneImage(resized_frame)
                        
        text_frame = cv.CloneImage(frame)
        cv.Zero(text_frame)
    
        while not rospy.is_shutdown():
            """ Handle keyboard events """
            self.keystroke = cv.WaitKey(1000 / fps)

            """ Process any keyboard commands """
            if 32 <= self.keystroke and self.keystroke < 128:
                cc = chr(self.keystroke).lower()
                if cc == 'q':
                    """ user has press the q key, so exit """
                    rospy.signal_shutdown("User hit q key to quit.")
                elif cc == ' ':
                    """ Pause or continue the video """
                    self.paused = not self.paused
                elif cc == 'r':
                    """ Restart the video from the beginning """
                    self.restart = True
                elif cc == 't':
                    """ Toggle display of text help message """
                    self.show_text = not self.show_text
                
            if self.restart:
                #video = cv.CaptureFromFile(self.input)
                print "restarting video from beginning"
                cv.SetCaptureProperty(video, cv.CV_CAP_PROP_POS_AVI_RATIO, 0)
                self.restart = None
    
            if not self.paused:
                frame = cv.QueryFrame(video)
                if frame and self.width and self.height:
                    if self.width != image_size[0] or self.height != image_size[1]:
                        cv.Resize(frame, resized_frame)
                        frame = cv.CloneImage(resized_frame)
                
            if frame == None:
                if self.loop:
                    self.restart = True
            else:
                if self.show_text:
                    frame_size = cv.GetSize(frame)
                    text_font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.2, 1, 0, 1, 8)
                    cv.PutText(text_frame, "Keyboard commands:", (20, int(frame_size[1] * 0.6)), text_font, cv.RGB(255, 255, 0))
                    cv.PutText(text_frame, " ", (20, int(frame_size[1] * 0.65)), text_font, cv.RGB(255, 255, 0))
                    cv.PutText(text_frame, "space - toggle pause/play", (20, int(frame_size[1] * 0.72)), text_font, cv.RGB(255, 255, 0))
                    cv.PutText(text_frame, "     r - restart video from beginning", (20, int(frame_size[1] * 0.79)), text_font, cv.RGB(255, 255, 0))
                    cv.PutText(text_frame, "     t - hide/show this text", (20, int(frame_size[1] * 0.86)), text_font, cv.RGB(255, 255, 0))
                    cv.PutText(text_frame, "     q - quit the program", (20, int(frame_size[1] * 0.93)), text_font, cv.RGB(255, 255, 0))
                
                cv.Add(frame, text_frame, text_frame)
                if self.show_viz:
                    cv.ShowImage("AVI Video", text_frame)
                cv.Zero(text_frame)
                
                try:
                    test = np.asarray(frame[:,:])
                    publishing_image = bridge.cv2_to_imgmsg(test, "bgr8")
                    image_pub.publish(publishing_image)
                except CvBridgeError, e:
                    print e         
#! /usr/bin/env python
"""
@author: Jesus Arturo Escobedo Cabello
@contact: [email protected]
"""
import cv2.cv as cv
import numpy as np

# class MyTestClass():
#    def __init__(self, x_length=10, y_length=10, origin=(0, 0), resolution=1):
#        self.grid = cv.CreateMat(self.height, self.width, cv.CV_32FC1)  # @var self.grid:  Opencv matrix;The actual grid
#

if __name__ == "__main__":

    cv.NamedWindow("mi grid", cv.CV_WINDOW_NORMAL)
    cv.NamedWindow("mi grid2", cv.CV_WINDOW_NORMAL)
    float_img = cv.CreateMat(10, 10, cv.CV_32FC1)
    float_img = cv.Load("interest_grid.xml", cv.CreateMemStorage())
    py_img = 1.0 * np.asarray(float_img)
    py_img = 255 * (py_img / np.max(py_img))
    img = cv.fromarray(py_img.astype(np.uint8))
    rgb_img = cv.CreateImage((img.cols, img.rows), 8, 4)
    """Creating RGB img"""
    img_r = cv.CloneMat(img)
    img_g = cv.CreateImage((img.cols, img.rows), 8, 1)
    img_b = cv.CreateImage((img.cols, img.rows), 8, 1)
    img_a = cv.CreateImage((img.cols, img.rows), 8, 1)
    cv.Set(img_g, 10)
    cv.Set(img_b, 100)
    cv.Set(img_a, 100)
Esempio n. 13
0
    return ipts

def mk_point_counts(nimages):
    npts = cv.CreateMat(nimages, 1, cv.CV_32SC1)
    for i in range(nimages):
        npts[i, 0] = num_pts
    return npts

def cvmat_iterator(cvmat):
    for i in range(cvmat.rows):
        for j in range(cvmat.cols):
            yield cvmat[i,j]

cam = Camera(3.0)
rend = Renderer(640, 480, 2)
cv.NamedWindow("snap")

#images = [rend.frame(i) for i in range(0, 2000, 400)]
images = [rend.frame(i) for i in [1200]]

if 0:
    for i,img in enumerate(images):
        cv.SaveImage("final/%06d.png" % i, img)

size = cv.GetSize(images[0])
corners = [get_corners(i) for i in images]

goodcorners = [co for (im, (ok, co)) in zip(images, corners) if ok]

def checkerboard_error(xformed):
    def pt2line(a, b, c):
Esempio n. 14
0
    def _process_movie(self, **kwargs):
        """
			Function for analyzing a full film or video. This is where the magic happens when we're making analyses. Function will exit if neither a movie path nor a data path are supplied. This function is not intended to be called directly. Normally, call one of the two analyze_ functions instead, which will call this function.
		
		"""

        ap = self._check_pcorr_params(kwargs)
        verbose = ap['verbose']

        if not HAVE_CV:
            print "WARNING: You must install OpenCV in order to analyze or view!"
            return

        if (self.movie_path is None) and (self.data_path is
                                          None) and ap['mode'] is 'analysis':
            print "ERROR: Must supply both a movie and a data path for analysis!"
            return

        have_mov = os.path.exists(self.movie_path)
        have_data = os.path.exists(self.data_path)

        if (have_mov is False) and (have_data is False):
            print "Both movie file and data file are missing! Please supply at least one."
            return None

        print ap

        if have_mov:
            self.capture = cv2.VideoCapture(self.movie_path)
            frame_width = int(self.capture.get(cv.CV_CAP_PROP_FRAME_WIDTH))
            frame_height = int(self.capture.get(cv.CV_CAP_PROP_FRAME_HEIGHT))
        else:
            frame_width = 640
            frame_height = int(frame_width / self._read_json_value('aspect'))

        fps = ap['fps']
        grid_x_divs = ap['grid_divs_x']
        grid_y_divs = ap['grid_divs_y']
        frame_size = (frame_width, frame_height)
        grid_width = int(frame_width / grid_x_divs)
        grid_height = int(frame_height / grid_y_divs)
        grid_size = (grid_width, grid_height)

        centers_x = range((frame_width / 16), frame_width, (frame_width / 8))
        centers_y = range((frame_height / 16), frame_height,
                          (frame_height / 8))

        if verbose:
            print fps, ' | ', frame_size, ' | ', grid_size

        # container for prev. frame's grayscale subframes
        prev_sub_grays = []

        if ap['offset'] > 0:
            offset_secs = ap['offset']
        else:
            offset_secs = 0

        print "%%% ", ap['duration']

        if ap['duration'] > 0:
            dur_secs = ap['duration']
        elif ap['duration'] < 0:
            ap['duration'] = self.determine_movie_length()
        else:
            print "Duration cannot be 0."
            return
        dur_secs = ap['duration']

        stride_frames = ap['stride']
        stride_hop = stride_frames - 1

        print "1. ", ap['duration']
        print "2. ", dur_secs

        # check offset first, then compress duration, if needed
        offset_secs = min(max(offset_secs, 0), ap['duration'])
        dur_secs = min(max(dur_secs, 0), (ap['duration'] - offset_secs))
        offset_strides = int(offset_secs * (fps / stride_frames))
        dur_strides = int(dur_secs * (fps / stride_frames))
        offset_frames = offset_strides * stride_frames
        dur_frames = dur_strides * stride_frames

        if verbose:
            print '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'
            print 'DUR TOTAL: ', dur_total_secs
            print "OFFSET (SECONDS): ", offset_secs
            print "OFFSET (STRIDES): ", offset_strides
            print "OFFSET (FRAMES): ", offset_frames
            print "DUR (SECONDS): ", dur_secs
            print 'DUR (STRIDES): ', dur_strides
            print 'DUR (FRAMES): ', dur_frames
            print 'XDIVS: ', grid_x_divs
            print 'YDIVS: ', grid_y_divs
            print "FPS: ", fps
            print "stride_frames: ", stride_frames

        # set up memmap
        if ap['mode'] == 'playback' and ap['display'] == True:
            fp = np.memmap(self.data_path,
                           dtype='float32',
                           mode='r',
                           shape=((offset_strides + dur_strides), (64 + 1), 2))
        else:
            fp = np.memmap(self.data_path,
                           dtype='float32',
                           mode='w+',
                           shape=(dur_strides, (64 + 1), 2))

        if ap['display']:
            cv.NamedWindow('Image', cv.CV_WINDOW_AUTOSIZE)
            cv.ResizeWindow('Image', frame_width, frame_height)

        self.frame_idx = offset_frames
        end_frame = offset_frames + dur_frames

        if have_mov:
            self.capture.set(cv.CV_CAP_PROP_POS_FRAMES, offset_frames)
            ret, frame = self.capture.read()
            if frame is None:
                print 'Frame error! Exiting...'
                return  # no image captured... end the processing
            frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            prev_frame_gray = np.float32(frame_gray[:])

            fhann = cv2.createHanningWindow((frame_width, frame_height),
                                            cv2.CV_32FC1)
            ghann = cv2.createHanningWindow((grid_width, grid_height),
                                            cv2.CV_32FC1)

            for row in range(grid_y_divs):
                for col in range(grid_x_divs):
                    prev_sub_grays += [
                        np.float32(frame_gray[(row *
                                               grid_height):((row + 1) *
                                                             grid_height),
                                              (col * grid_width):((col + 1) *
                                                                  grid_width)])
                    ]

        else:
            frame = np.empty((frame_width, frame_height), np.uint8)
            print frame.shape

        self.frame_idx += 1

        print "<<< ", frame.mean()
        # 		cv.ShowImage('Image', cv.fromarray(frame))

        while self.frame_idx < end_frame:

            if (self.frame_idx % 1000) == 0:
                print 'fr. idx: ', self.frame_idx, ' (', self.frame_idx / float(
                    end_frame), ' | ', end_frame, ')'

            if have_mov:
                # grab next frame
                ret, frame = self.capture.read()
                if frame is None:
                    print 'Frame error! Exiting...'
                    break  # no image captured... end the processing
                frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            else:
                frame[:] = 0

            # display stage (full)
            if ap['mode'] == 'playback' and ap['display']:
                fret = fp[self.frame_idx][64]
                # print fret
            elif have_mov:
                fret, fres = cv2.phaseCorrelateRes(prev_frame_gray,
                                                   np.float32(frame_gray[:]),
                                                   fhann)
                print fret
                if abs(fres) > 0.01:
                    fp[self.frame_idx][64] = [(fret[0] / frame_width),
                                              (fret[1] / frame_height)]
                else:
                    fp[self.frame_idx][64] = [0, 0]
            else:
                return

            # display stage (gridded)
            for row in range(grid_y_divs):
                for col in range(grid_x_divs):
                    if ap['mode'] == 'playback' and ap['display']:
                        cell = ((row * 8) + col)
                        gret = fp[self.frame_idx][cell]
                    elif have_mov:
                        sub_gray = np.float32(
                            frame_gray[(row * grid_height):((row + 1) *
                                                            grid_height),
                                       (col * grid_width):((col + 1) *
                                                           grid_width)][:])
                        gret, gres = cv2.phaseCorrelateRes(
                            prev_sub_grays[(row * grid_x_divs) + col],
                            sub_gray, ghann)
                        prev_sub_grays[(row * grid_x_divs) + col] = sub_gray
                        if abs(gres) > 0.7:  # WAS 0.01!!!!
                            fp[self.frame_idx][(row * grid_x_divs) + col] = [
                                (gret[0] / grid_width), (gret[1] / grid_height)
                            ]
                        else:
                            fp[self.frame_idx][(row * grid_x_divs) +
                                               col] = [0, 0]
                    else:
                        return

                    if ap['display'] and (gret[0] != 0 and gret[1] != 0):
                        print gret
                        print grid_size
                        print centers_x[col]
                        print centers_y[row]
                        xval = int(
                            min((gret[0] * 1000), grid_size[0]) +
                            centers_x[col])
                        yval = int(
                            min((gret[1] * 1000), grid_size[1]) +
                            centers_y[row])
                        # print ((centers_x[i], centers_y[j], xval, yval), False, (0,255,255))
                        print(centers_x[col], centers_y[row])
                        print(xval, yval)
                        cv2.line(frame, (centers_x[col], centers_y[row]),
                                 (xval, yval), (255, 255, 255))

            #### SHOW
            if ap['display'] and have_mov:
                print "<<< ", frame.mean()
                cv.ShowImage('Image', cv.fromarray(frame))
            fp.flush()

            self.frame_idx += 1
            if have_mov:
                self.prev_gray = np.float32(frame_gray[:])

            # handle events for abort
            k = cv.WaitKey(int(1000 / ap['afps']))
            if k % 0x100 == 27:
                # user has press the ESC key, so exit
                break

        del fp
        if ap['display']:
            cv2.destroyAllWindows()
Esempio n. 15
0
    a = 0.055
    return numpy.where(x <= 0.0031308, x * 12.92,
                       (1 + a) * numpy.power(x, 1 / 2.4) - a)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        img0 = cv.LoadImageM(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR)
    else:
        url = 'http://code.opencv.org/svn/opencv/trunk/opencv/samples/c/lena.jpg'
        filedata = urllib2.urlopen(url).read()
        imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
        cv.SetData(imagefiledata, filedata, len(filedata))
        img0 = cv.DecodeImageM(imagefiledata, cv.CV_LOAD_IMAGE_COLOR)

    cv.NamedWindow("original", 1)
    cv.ShowImage("original", img0)

    # Image was originally bytes in range 0-255.  Turn it into an array of floats in range 0.0 - 1.0
    n = numpy.asarray(img0) / 255.0

    # Use NumPy to do some transformations on the image

    # Negate the image by subtracting it from 1.0
    cv.NamedWindow("negative")
    cv.ShowImage("negative", cv.fromarray(1.0 - n))

    # Assume the image was sRGB, and compute the linear version.
    cv.NamedWindow("linear")
    cv.ShowImage("linear", cv.fromarray(srgb2lin(n)))
Esempio n. 16
0
if __name__ == "__main__":
    motion = 0
    capture = 0

    if len(sys.argv) == 1:
        capture = cv.CreateCameraCapture(0)
    elif len(sys.argv) == 2 and sys.argv[1].isdigit():
        capture = cv.CreateCameraCapture(int(sys.argv[1]))
    elif len(sys.argv) == 2:
        capture = cv.CreateFileCapture(sys.argv[1])

    if not capture:
        print "Could not initialize capturing..."
        sys.exit(-1)

    cv.NamedWindow("Motion", 1)
    while True:
        image = cv.QueryFrame(capture)
        if (image):
            if (not motion):
                motion = cv.CreateImage((image.width, image.height), 8, 3)
                cv.Zero(motion)
                #motion.origin = image.origin
            update_mhi(image, motion, 30)
            cv.ShowImage("Motion", motion)
            if (cv.WaitKey(10) != -1):
                break
        else:
            break
    cv.DestroyWindow("Motion")
Esempio n. 17
0
# toggle between CV_HOUGH_STANDARD and CV_HOUGH_PROBILISTIC
USE_STANDARD = True

if __name__ == "__main__":
    if len(sys.argv) > 1:
        filename = sys.argv[1]
        src = cv.LoadImage(filename, cv.CV_LOAD_IMAGE_GRAYSCALE)
    else:
        url = 'http://code.opencv.org/projects/opencv/repository/revisions/master/raw/doc/pics/building.jpg'
        filedata = urllib2.urlopen(url).read()
        imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
        cv.SetData(imagefiledata, filedata, len(filedata))
        src = cv.DecodeImageM(imagefiledata, cv.CV_LOAD_IMAGE_GRAYSCALE)

    cv.NamedWindow("Source", 1)
    cv.NamedWindow("Hough", 1)

    while True:
        dst = cv.CreateImage(cv.GetSize(src), 8, 1)
        color_dst = cv.CreateImage(cv.GetSize(src), 8, 3)
        storage = cv.CreateMemStorage(0)
        lines = 0
        cv.Canny(src, dst, 50, 200, 3)
        cv.CvtColor(dst, color_dst, cv.CV_GRAY2BGR)

        if USE_STANDARD:
            lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_STANDARD, 1,
                                   pi / 180, 100, 0, 0)
            for (rho, theta) in lines[:100]:
                a = cos(theta)
Esempio n. 18
0
import cv2.cv as cv
from random import randint
MAX_CLUSTERS = 5

if __name__ == "__main__":

    color_tab = [
        cv.CV_RGB(255, 0,0),
        cv.CV_RGB(0, 255, 0),
        cv.CV_RGB(100, 100, 255),
        cv.CV_RGB(255, 0,255),
        cv.CV_RGB(255, 255, 0)]
    img = cv.CreateImage((500, 500), 8, 3)
    rng = cv.RNG(-1)

    cv.NamedWindow("clusters", 1)

    while True:
        cluster_count = randint(2, MAX_CLUSTERS)
        sample_count = randint(1, 1000)
        points = cv.CreateMat(sample_count, 1, cv.CV_32FC2)
        clusters = cv.CreateMat(sample_count, 1, cv.CV_32SC1)

        # generate random sample from multigaussian distribution
        for k in range(cluster_count):
            center = (cv.RandInt(rng)%img.width, cv.RandInt(rng)%img.height)
            first = k*sample_count/cluster_count
            last = sample_count
            if k != cluster_count:
                last = (k+1)*sample_count/cluster_count
Esempio n. 19
0
    parser.add_option("-c", "--cascade", action="store", dest="cascade", type="str", help="Haar cascade file, default %default", default = "../data/haarcascades/haarcascade_frontalface_alt.xml")
    (options, args) = parser.parse_args()

    cascade = cv.Load(options.cascade)

    if len(args) != 1:
        parser.print_help()
        sys.exit(1)
 
    input_name = args[0]
    if input_name.isdigit():
        capture = cv.CreateCameraCapture(int(input_name))
    else:
        capture = None

    cv.NamedWindow("video", 1)

    #size of the video
    width = 160
    height = 120

    if width is None:
        width = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH))
    else:
        cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_WIDTH,width)

    if height is None:
    	height = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT))
    else:
	cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_HEIGHT,height)
Esempio n. 20
0
x_co = 0
y_co = 0


def on_mouse(event, x, y, flag, param):
    global x_co
    global y_co
    if (event == cv.CV_EVENT_MOUSEMOVE):
        x_co = x
        y_co = y


cap = cv2.VideoCapture("http://192.168.1.2:8080/videofeed?dummy=file.mjpeg")

cv.NamedWindow('HSV', cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow('HS_', cv.CV_WINDOW_AUTOSIZE)

# running the classifiers
storage = cv.CreateMemStorage()

while True:

    _, frame = cap.read()
    #frame = cv2.medianBlur(frame,5)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    hsv[:, :, 2] = 0
    cv2.imshow('HSV', hsv)
    # hsv[:,:,1] = cv2.threshold(hsv[:,:,1], 65, 255, cv2.THRESH_BINARY)
    # TR_MIN = np.array([5, 50, 50],np.uint8)
    # TR_MAX = np.array([15, 255, 255],np.uint8)
Esempio n. 21
0
 def snapL(self, L):
     for i,img in enumerate(L):
         cv.NamedWindow("snap-%d" % i, 1)
         cv.ShowImage("snap-%d" % i, img)
     cv.WaitKey()
     cv.DestroyAllWindows()
Esempio n. 22
0
    if len(sys.argv) > 1:
        img0 = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR)
    else:
        url = 'https://raw.github.com/opencv/opencv/master/samples/c/fruits.jpg'
        filedata = urllib2.urlopen(url).read()
        imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
        cv.SetData(imagefiledata, filedata, len(filedata))
        img0 = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR)

    print "Hot keys:"
    print "\tESC - quit the program"
    print "\tr - restore the original image"
    print "\ti or ENTER - run inpainting algorithm"
    print "\t\t(before running it, paint something on the image)"

    cv.NamedWindow("image", 1)
    cv.NamedWindow("inpainted image", 1)

    img = cv.CloneImage(img0)
    inpainted = cv.CloneImage(img0)
    inpaint_mask = cv.CreateImage(cv.GetSize(img), 8, 1)

    cv.Zero(inpaint_mask)
    cv.Zero(inpainted)
    cv.ShowImage("image", img)
    cv.ShowImage("inpainted image", inpainted)

    sk = Sketcher("image", [img, inpaint_mask])
    while True:
        c = cv.WaitKey(0) % 0x100
import cv2
import cv2.cv as cv

cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)

def repeat():

    frame = cv.QueryFrame(capture)

    
    cv.ShowImage("w1", frame)

    c = cv.WaitKey(100)
    if(c != -1):
        while True:
            c = cv.WaitKey(100)
            if(c != -1):
                break


repeat()
cv2.destroyAllWindows()
del(capture)
Esempio n. 24
0
            cv.CV_WARP_FILL_OUTLIERS + cv.CV_WARP_INVERSE_MAP)
        cv.ShowImage("log-polar", dst)
        cv.ShowImage("inverse log-polar", src2)


if __name__ == "__main__":

    if len(sys.argv) > 1:
        src = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR)
    else:
        url = 'https://raw.github.com/opencv/opencv/master/samples/c/fruits.jpg'
        filedata = urllib2.urlopen(url).read()
        imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
        cv.SetData(imagefiledata, filedata, len(filedata))
        src = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR)

    cv.NamedWindow("original", 1)
    cv.NamedWindow("log-polar", 1)
    cv.NamedWindow("inverse log-polar", 1)

    dst = cv.CreateImage((256, 256), 8, 3)
    src2 = cv.CreateImage(cv.GetSize(src), 8, 3)

    cv.SetMouseCallback("original", on_mouse)
    on_mouse(cv.CV_EVENT_LBUTTONDOWN, src.width / 2, src.height / 2, None,
             None)

    cv.ShowImage("original", src)
    cv.WaitKey()
    cv.DestroyAllWindows()
Esempio n. 25
0
if __name__ == '__main__':
  capture = cv.CaptureFromCAM(0)
  #capture = cv.CaptureFromFile("out.mpg") # not working, for unknown reasons

  cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 320)
  cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 240)

  polar = cv.CreateImage((360, 360), 8, 3)
  img = cv.CreateImage((320, 240), 8, 3)
  im = cv.CreateImage((320, 240), 8, 1)
  rt = cv.CreateImage((320, 240), 8, 1)
  lt = cv.CreateImage((320, 240), 8, 1)
  lm = cv.LoadImageM("leftmask-K-2013-02-27.bmp", cv.CV_LOAD_IMAGE_GRAYSCALE)
  rm = cv.LoadImageM("rightmask-K-2013-02-27.bmp", cv.CV_LOAD_IMAGE_GRAYSCALE)
  
  cv.NamedWindow('cam')
  cv.NamedWindow('left')
  cv.NamedWindow('right')

  cv.SetMouseCallback("cam", on_mouse)
  on_mouse(cv.CV_EVENT_LBUTTONDOWN, centerX, centerY, None, None)

  font = cv.InitFont(cv.CV_FONT_HERSHEY_PLAIN, 1.0, 1.0) 

  M = 60

  while True:
    img = cv.QueryFrame(capture)
    cv.CvtColor(img, im, cv.CV_RGB2GRAY)
    #cv.LogPolar(img, polar, (centerX, centerY), M+1, cv.CV_INTER_NN + cv.CV_WARP_FILL_OUTLIERS )
Esempio n. 26
0
    contours = cv.FindContours(img_result, storage,  cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)
    print contours
    # draw contours in red and green
    cv.DrawContours (img_result, #dest image
        contours, #input contours
        _red, #color of external contour
        _green, #color of internal contour
        levels, #maxlevel of contours to draw
        _contour_thickness,
        cv.CV_AA, #line type
        (0, 0)) #offset
    pass

def on_trackbar_smooth(position):
    cv.Smooth(img_gray, img_gray, smoothtype=cv.CV_BLUR, param1=2*position+1)
    pass

src_file = 'runtime/hand_color.jpg'
src_img = cv.LoadImage(src_file)
src_img_size = cv.GetSize(src_img)
img_gray = cv.CreateImage(src_img_size, 8, 1)
cv.CvtColor(src_img, img_gray, cv.CV_BGR2GRAY)
cv.NamedWindow("converted-image", 1)
cv.ShowImage("converted-image", img_gray)
cv.Smooth(img_gray, img_gray, smoothtype=cv.CV_BLUR)
cv.NamedWindow("contours", 1)
print cv.CreateTrackbar("(pre) smoothness", 'contours', 0, 7, on_trackbar_smooth)
print cv.CreateTrackbar ("canny threshold", "contours", 0, 7, on_trackbar)
cv.ShowImage("contours", img_gray)
cv.WaitKey(0)
Esempio n. 27
0
import cv2.cv as cv
import time

cv.NamedWindow("camera", 1)
capture = cv.CaptureFromCAM(0)

while True:
    img = cv.QueryFrame(capture)
    cv.ShowImage("camera", img)

    cv.SaveImage('test1.jpg', img)

    if cv.WaitKey(10) == 27:
        break
cv.DestroyAllWindows()
Esempio n. 28
0
    (win_size, win_size),
    5,
    (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 20, 0.03),
    0
);
# Now make some image of what we are looking at:
#
for i in range(100):
    if (features_found[i] == 0 or feature_errors[i] > 550):
    # printf("Error is %f/n",feature_errors[i]);
    continue;

    print("Got it");

    p0 = (
        cv.Round(cornersA[i][1]),  # how ot get the (x, y)
        cv.Round(cornersA[i][1])
    )
    p1 = (
        cv.Round(cornersB[i][1]),
        cv.Round(cornersB[i][1])
    )
    cv.Line(imgC, p0, p1, cv.CV_RGB(255, 0, 0), 2);

cv.NamedWindow("ImageA", 0);
cv.NamedWindow("ImageB", 0);
cv.NamedWindow("LKpyr_OpticalFlow", 0);
cv.ShowImage("ImageA", imgA);
cv.ShowImage("ImageB", imgB);
cv.ShowImage("LKpyr_OpticalFlow", imgC);
cv.WaitKey(0);
        default="./data/haarcascades/haarcascade_frontalface_alt.xml")
    (options, args) = parser.parse_args()

    cascade = cv.Load(options.cascade)

    if len(args) != 1:
        parser.print_help()
        sys.exit(1)

    input_name = args[0]
    if input_name.isdigit():
        capture = cv.CreateCameraCapture(int(input_name))
    else:
        capture = None

    cv.NamedWindow("result", 1)

    if capture:
        frame_copy = None
        while True:
            frame = cv.QueryFrame(capture)
            if not frame:
                cv.WaitKey(0)
                break
            if not frame_copy:
                frame_copy = cv.CreateImage((frame.width, frame.height),
                                            cv.IPL_DEPTH_8U, frame.nChannels)
            if frame.origin == cv.IPL_ORIGIN_TL:
                cv.Copy(frame, frame_copy)
            else:
                cv.Flip(frame, frame_copy, 0)
Esempio n. 30
0
    s_bins = 32
    hist_size = [h_bins, s_bins]
    # hue varies from 0 (~0 deg red) to 180 (~360 deg red again */
    h_ranges = [0, 180]
    # saturation varies from 0 (black-gray-white) to
    # 255 (pure spectrum color)
    s_ranges = [0, 255]
    ranges = [h_ranges, s_ranges]
    scale = 10
    hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1)
    cv.CalcHist([cv.GetImage(i) for i in planes], hist)
    (_, max_value, _, _) = cv.GetMinMaxHistValue(hist)
    hist_img = cv.CreateImage((h_bins * scale, s_bins * scale), 8, 3)
    for h in range(h_bins):
        for s in range(s_bins):
            bin_val = cv.QueryHistValue_2D(hist, h, s)
            intensity = cv.Round(bin_val * 255 / max_value)
            cv.Rectangle(hist_img, (h * scale, s * scale),
                         ((h + 1) * scale - 1, (s + 1) * scale - 1),
                         cv.RGB(intensity, intensity, intensity), cv.CV_FILLED)
    return hist_img


if __name__ == '__main__':
    src = cv.LoadImage("E:\\python workspace\\Charlie\\eye2.png")
    cv.NamedWindow("Source", 1)
    cv.ShowImage("Source", src)
    cv.NamedWindow("H-S Histogram", 1)
    cv.ShowImage("H-S Histogram", hs_histogram(src))
    cv.WaitKey(0)