예제 #1
0
    def __init__(self, node_name):
        ROS2OpenCV2.__init__(self, node_name)

        self.node_name = node_name
        
        # The minimum saturation of the tracked color in HSV space,
        # as well as the min and max value (the V in HSV) and a 
        # threshold on the backprojection probability image.
        self.smin = rospy.get_param("~smin", 85)
        self.vmin = rospy.get_param("~vmin", 50)
        self.vmax = rospy.get_param("~vmax", 254)
        self.threshold = rospy.get_param("~threshold", 50)
                       
        # Create a number of windows for displaying the histogram,
        # parameters controls, and backprojection image
        cv.NamedWindow("Histogram", cv.CV_WINDOW_NORMAL)
        cv.MoveWindow("Histogram", 700, 50)
        cv.NamedWindow("Parameters", 0)
        cv.MoveWindow("Parameters", 700, 325)
        cv.NamedWindow("Backproject", 0)
        cv.MoveWindow("Backproject", 700, 600)
        
        # Create the slider controls for saturation, value and threshold
        cv.CreateTrackbar("Saturation", "Parameters", self.smin, 255, self.set_smin)
        cv.CreateTrackbar("Min Value", "Parameters", self.vmin, 255, self.set_vmin)
        cv.CreateTrackbar("Max Value", "Parameters", self.vmax, 255, self.set_vmax)
        cv.CreateTrackbar("Threshold", "Parameters", self.threshold, 255, self.set_threshold)
        
        # Initialize a number of variables
        self.hist = None
        self.track_window = None
        self.show_backproj = False
예제 #2
0
    def __init__(self):
        self.node_name = "cv_bridge_demo"

        rospy.init_node(self.node_name)

        # What we do during shutdown
        rospy.on_shutdown(self.cleanup)

        # Create the OpenCV display window for the RGB image
        self.cv_window_name = self.node_name
        cv2.NamedWindow(self.cv_window_name, cv2.CV_WINDOW_NORMAL)
        cv2.MoveWindow(self.cv_window_name, 25, 75)

        # And one for the depth image
        cv2.NamedWindow("Depth Image", cv2.CV_WINDOW_NORMAL)
        cv2.MoveWindow("Depth Image", 25, 350)

        # Create the cv_bridge object
        self.bridge = CvBridge()

        # Subscribe to the camera image and depth topics and set
        # the appropriate callbacks
        self.image_sub = rospy.Subscriber("/bebop/image_raw", Image,
                                          self.image_callback)
        self.depth_sub = rospy.Subscriber("/camera/depth/image_raw", Image,
                                          self.depth_callback)

        rospy.loginfo("Waiting for image topics...")
예제 #3
0
    def initialize(self, filename, verbose=0):
        self._InitConfig(filename)
        self._verbose = verbose

        if self._verbose:
            cv2.NamedWindow('src_image', cv2.CV_WINDOW_AUTOSIZE)
            cv2.MoveWindow('src_image', 50, 50)
            cv2.NamedWindow('dst_image', cv2.CV_WINDOW_AUTOSIZE)
            cv2.MoveWindow('des_image', 50, 350)
예제 #4
0
 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)
예제 #5
0
    def __init__(self, ceil=8, doRecord=True, showWindows=True):
        self.writer = None
        self.font = None
        self.doRecord = doRecord  #Either or not record the moving object
        self.show = showWindows  #Either or not show the 2 windows
        self.frame = None

        self.capture = cv.VideoCapture(0)
        self.frame = self.capture.read()  #Take a frame to init recorder
        if doRecord:
            self.initRecorder()

        self.frame1gray = cv.CreateMat(self.frame.height, self.frame.width,
                                       cv.CV_8U)  #Gray frame at t-1
        cv.CvtColor(self.frame, self.frame1gray, cv.CV_RGB2GRAY)

        #Will hold the thresholded result
        self.res = cv.CreateMat(self.frame.height, self.frame.width, cv.CV_8U)

        self.frame2gray = cv.CreateMat(self.frame.height, self.frame.width,
                                       cv.CV_8U)  #Gray frame at t

        self.width = self.frame.width
        self.height = self.frame.height
        self.nb_pixels = self.width * self.height
        self.ceil = ceil
        self.isRecording = False
        self.trigger_time = 0  #Hold timestamp of the last detection

        if showWindows:
            cv.NamedWindow("Image")
            cv.CreateTrackbar("Mytrack", "Image", self.ceil, 100,
                              self.onChange)
예제 #6
0
    def __init__(self, threshold=1, doRecord=True, showWindows=True):
        self.writer = None
        self.font = None
        self.doRecord = doRecord  # Either or not record the moving object
        self.show = showWindows  # Either or not show the 2 windows
        self.frame = None

        self.capture = cv.CaptureFromCAM(0)
        self.frame = cv.QueryFrame(
            self.capture)  # Take a frame to init recorder
        if doRecord:
            self.initRecorder()
        self.gray_frame = cv.CreateImage(cv.GetSize(self.frame),
                                         cv.IPL_DEPTH_8U, 1)
        self.average_frame = cv.CreateImage(cv.GetSize(self.frame),
                                            cv.IPL_DEPTH_32F, 3)
        self.absdiff_frame = None
        self.previous_frame = None

        self.surface = self.frame.width * self.frame.height
        self.currentsurface = 0
        self.currentcontours = None
        self.threshold = threshold
        self.isRecording = False
        self.trigger_time = 0  # Hold timestamp of the last detection
        if showWindows:
            cv.NamedWindow("Image")
            cv.CreateTrackbar("Detection treshold: ", "Image", self.threshold,
                              100, self.onThresholdChange)
  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 grab_images(video_file, frame_inc=100, delay=100):
    """
    Walks through the entire video and save image for each increment
    """
    my_video = init_video(video_file)
    if my_video != None:
        # Display the video and save evry increment frames
        cpt = 0
        img = cv2.QueryFrame(my_video)

        if img != None:
            cv2.NamedWindow("Vid", cv2.CV_WINDOW_AUTOSIZE)
        else:
            return None

        nFrames = int(
            cv2.GetCaptureProperty(my_video, cv2.CV_CAP_PROP_FRAME_COUNT))
        while cpt < nFrames:
            for ii in range(frame_inc):
                img = cv2.QueryFrame(my_video)
                cpt += 1

            cv2.ShowImage("Vid", img)
            out_name = "" + str(cpt) + ".jpg"
            cv2.SaveImage(out_name, img)
            print out_name, str(nFrames)
            cv2.WaitKey(delay)
    else:
        return None
def display_video(my_video, frame_inc=100, delay=100):
    """
    Displays frames of the video in a dumb way.
    Used to see if everything is working fine
    my_video = cv2Capture object
    frame_inc = Nmber of increments between each frame displayed
    delay = time delay between each image 
    """
    cpt = 0
    img = cv2.QueryFrame(my_video)

    if img != None:
        cv2.NamedWindow("Vid", cv2.CV_WINDOW_AUTOSIZE)
    else:
        return None

    nFrames = int(cv2.GetCaptureProperty(my_video,
                                         cv2.CV_CAP_PROP_FRAME_COUNT))
    while cpt < nFrames:
        for ii in range(frame_inc):
            img = cv2.QueryFrame(my_video)
            cpt + 1

        cv2.ShowImage("Vid", img)
        cv2.WaitKey(delay)
def display_img(img, delay=1000):
    """
    One liner that displays the given image on screen
    """
    cv2.NamedWindow("Vid", cv2.CV_WINDOW_AUTOSIZE)
    cv2.ShowImage("Vid", img)
    cv2.WaitKey(delay)
예제 #11
0
def show(area):
    cv2.Rectangle(img, (area[0][0], area[0][1]),
                  (area[0][0] + area[0][2], area[0][1] + area[0][3]),
                  (255, 0, 0), 2)
    cv2.NamedWindow('Face Detection', cv2.CV_WINDOW_NORMAL)
    cv2.imread('Face Detection', img)
    cv2.WaitKey()
예제 #12
0
    def use_camera(self):
        # global cascade, capture, frame_copy
        if not self.is_device_connected():
            return

        try:

            # if camera already openned
            if self.capture is not None:
                return

            if self.cascade is None:
                self.cascade = cv.Load(
                    os.path.join(APPLICATION_PATH, "face.xml"))

            self.capture = cv.CreateCameraCapture(0)

            if self.showVideo:
                cv.NamedWindow("video", 1)

            self.set_resolution(640, 480)

            self.frame_copy = None

        except:
            self.close_camera()
            print "Error in use_camera"
            pass
예제 #13
0
 def __init__(self,mode=1,name="w1",capture=1):
     print name
     if mode == 1:
         cv2.StartWindowThread()
         cv2.NamedWindow(name, cv2.CV_WINDOW_AUTOSIZE)
     self.camera_index = 0
     self.name=name
     if capture == 1:
         self.capture = cv2.CaptureFromCAM(self.camera_index)
 def draw_model_fitter(f):
   cv.NamedWindow("Model Fitter", cv.CV_WINDOW_AUTOSIZE)
   # Copy image
   i = cv.CreateImage(cv.GetSize(f.image), f.image.depth, 3)
   cv.Copy(f.image, i)
   for pt_num, pt in enumerate(f.shape.pts):
     # Draw normals
     cv.Circle(i, (int(pt.x), int(pt.y)), 2, (0,0,0), -1)
   cv.ShowImage("Shape Model",i)
   cv.WaitKey()
예제 #15
0
    def __init__(self,
                 webcam=0,
                 sample_duration=10,
                 window_title="Heart Monitor"):
        """
		Program to monitor heartrates using a webcam.
		"""

        self.cam = Camera(webcam)
        self.face_detector = FaceDetector(*self.cam.get_size())
        self.face_tracker = None
        self.heart_monitor = HeartMonitor(sample_duration,
                                          fps=self.cam.get_fps())
        self.annotator = Annotator()
        self.window = window_title

        cv.NamedWindow(self.window)

        self.show_bpm = True
        self.show_face = True
        self.show_forehead = True
        self.show_fft = True
예제 #16
0
    def __init__(self):
        self.node_name = "cv_bridge_demo"
        rospy.init_node(self.node_name)
        # What we do during shutdown
        rospy.on_shutdown(self.cleanup)
        # Create the OpenCV display window for the RGB image
        self.cv_window_name = self.node_name
        cv2.NamedWindow(self.cv_window_name, cv2.CV_WINDOW_NORMAL)
        cv2.MoveWindow(self.cv_window_name, 25, 75)

        # Create the cv_bridge object
        self.bridge = CvBridge()

        # Subscribe to the camera image and depth topics and set
        # the appropriate callbacks
        self.image_sub = rospy.Subscriber("/usb_cam/image_raw",
                                          Image,
                                          self.image_callback,
                                          queue_size=1)

        rospy.loginfo("Waiting for image topics...")
        rospy.wait_for_message("/usb_cam/image_raw", Image)
        rospy.loginfo("Ready.")
예제 #17
0
#### end of Detect faces ######################


def getColor(mf):
    if (mf.isNodding()): return GREEN
    elif (mf.isShaking()): return RED
    elif (mf.isStill()): return BLUE
    else: return YELLOW


######### main program ############
if __name__ == '__main__':

    #create window and move to screen position
    cv2.NamedWindow('Camera', cv2.CV_WINDOW_AUTOSIZE)
    cv2.namedWindow('Camera', cv2.WINDOW_AUTOSIZE)
    if len(sys.argv) == 1:
        # no argument on the command line, try to use the camera
        capture = cv2.CreateCameraCapture(0)
    #
    ### check that capture device is OK
    if not capture:
        print("Error opening capture device")
        sys.exit(1)
    #
    ### capture the 1st frame to get some propertie on it
    frame = cv2.QueryFrame(capture)
    #
    ### get size of the frame
    frame_size = cv2.GetSize(frame)
예제 #18
0
def main():

    global current_image
    global current_img_file_name
    global has_roi
    global roi_x0
    global roi_y0
    global roi_x1
    global roi_y1

    iKey = 0

    files = glob.glob(image_file_glob)
    if len(files) == 0:
        print("No files match glob pattern")
        return

    files = [os.path.abspath(f) for f in files]
    files.sort()

    # init GUI
    cv.NamedWindow(window_name, 1)
    cv.SetMouseCallback(window_name, on_mouse, None)

    sys.stderr.write("Opening directory...")
    # init output of rectangles to the info file
    #os.chdir(input_directory)
    sys.stderr.write("done.\n")

    current_file_index = 0

    while True:

        current_img_file_name = files[current_file_index]

        num_of_rec = 0
        sys.stderr.write(
            "Loading current_image (%d/%d) %s...\n" %
            (current_file_index + 1, len(files), current_img_file_name))

        try:
            current_image = cv.LoadImage(current_img_file_name, 1)
        except IOError:
            sys.stderr.write("Failed to load current_image %s.\n" %
                             current_img_file_name)
            return -1

        #  Work on current current_image
        #cv.ShowImage(window_name, current_image)
        redraw()

        # Need to figure out waitkey returns.
        # <Space> =  32     add rectangle to current image
        # <left>  =  81     save & next
        # <right> =  83     save & prev
        # <a>     =  97     add rect to table
        # <b>     =  98     toggle file is background or not
        # <d>     = 100     remove old rect
        # <q>     = 113     exit program
        # <s>     = 115     save rect table
        # <x>     = 136     skip image
        iKey = cv.WaitKey(0) % 255
        # This is ugly, but is actually a simplification of the C++.
        #sys.stderr.write(str(iKey) + '\n')
        if draging:
            continue

        if iKey == 81:
            current_file_index -= 1
            if current_file_index == -1:
                current_file_index = len(files) - 1
            clear_roi()
        elif iKey == 83:
            current_file_index += 1
            if current_file_index == len(files):
                current_file_index = 0
            clear_roi()
        elif iKey == 113:
            cv.DestroyWindow(window_name)
            return 0
        elif iKey == 97:
            rect_table.setdefault(current_img_file_name, set()).add(
                (roi_x0, roi_y0, roi_x1 - roi_x0, roi_y1 - roi_y0))
            clear_roi()
            write_rect_table()
            redraw()
        elif iKey == 98:
            if current_img_file_name in background_files:
                background_files.remove(current_img_file_name)
            else:
                background_files.add(current_img_file_name)
        elif iKey == 100:
            remove_rect(cur_mouse_x, cur_mouse_y)
        elif iKey == 115:
            write_rect_table()
        elif iKey == 136:
            sys.stderr.write("Skipped %s.\n" % current_file_index)
예제 #19
0
 def __init__(self, ceil=15):
     self.ceil = ceil
     self.capture = cv.CaptureFromCAM(0)
     cv.NamedWindow("Target", 1)
예제 #20
0
    for i in range(im.height):
        row = cv.GetRow(im, i)
        if cv.Sum(row)[0] != 0.0:
            bottommost = i
            if temp == 1:
                topmost = i
                temp = 2
    return (leftmost, rightmost, topmost, bottommost)


capture = cv.VideoCapture(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 1280)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 720)
frame = cv.QueryFrame(capture)
test = cv.CreateImage(cv.GetSize(frame), 8, 3)
cv.NamedWindow("output")
previous_x = 0
previous_y = 0
while (1):
    frame = cv.QueryFrame(capture)
    cv.Flip(frame, frame, 1)
    # we make all drawings on imdraw.
    imdraw = cv.CreateImage(cv.GetSize(frame), 8, 3)
    # we get coordinates from imgyellowthresh
    imgyellowthresh = getthresholdedimg(frame)
    # eroding removes small noises
    cv.Erode(imgyellowthresh, imgyellowthresh, None, 1)
    (leftmost, rightmost, topmost, bottommost) = getpositions(imgyellowthresh)
    if (leftmost - rightmost != 0) or (topmost - bottommost != 0):
        lastx = posx
        lasty = posy
예제 #21
0
파일: Morphw.py 프로젝트: nipponnp/aboutme
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)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        src = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR)
    else:
        url = 'https://code.ros.org/svn/opencv/trunk/opencv/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)

    image = cv.CloneImage(src)
    dest = cv.CloneImage(src)
    cv.NamedWindow("Opening & Closing", 1)
    cv.NamedWindow("Erosion & Dilation", 1)
    cv.ShowImage("Opening & Closing", src)
    cv.ShowImage("Erosion & Dilation", src)
    cv.CreateTrackbar("Open", "Opening & Closing", 0, 10, Opening)
    cv.CreateTrackbar("Close", "Opening & Closing", 0, 10, Closing)
    cv.CreateTrackbar("Dilate", "Erosion & Dilation", 0, 10, Dilation)
    cv.CreateTrackbar("Erode", "Erosion & Dilation", 0, 10, Erosion)
    cv.WaitKey(0)
    cv.DestroyWindow("Opening & Closing")
    cv.DestroyWindow("Erosion & Dilation")
예제 #22
0
    for x in range(18):
        set_pixel_rgbw(x, r if x in [3, 4] else 0, g if x in [3, 4] else 0, b,
                       w if x in [0, 1, 6, 7] else 0)
    show()


lights(0, 0, 0, 50)

min_size = (15, 15)
image_scale = 5
haar_scale = 1.2
min_neighbors = 2
haar_flags = cv.CASCADE_DO_CANNY_PRUNING

cap = cv.VideoCapture(0)
cv.NamedWindow("Tracker", 1)

if cap:
    frame_copy = None

while (True):
    # Capture frame-by-frame
    result, frame = capture.read()
    #frame = cv.QueryFrame(cap)
    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:
예제 #23
0
import os
import cv2
cv2.NamedWindow('image')
while true:
    os.system('fswebcam -r 1024')
예제 #24
0
    cv.Set2D(disparity,i,j,cv.Get2D(image,i,j)) #Change the particular array element.

# loading the stereo pair
left  = cv.imread('000000.png',cv.IMREAD_GRAYSCALE)
right = cv.imread('000001.png',cv.IMREAD_GRAYSCALE)

#create a matrix from each image
'''
disparity_left  = cv.CreateMat(left.height, left.width, cv.CV_16S)
disparity_right = cv.CreateMat(left.height, left.width, cv.CV_16S)
'''
disparity_left  = np.array((left.shape[0], left.shape[1]),np.uint8) #maybe changed to more approprate type
disparity_right = np.array((right.shape[0], right.shape[1]),np.uint8)

# Creates the state of graph cut-based stereo correspondence algorithm.
state = cv.CreateStereoGCState(16,2)
# Computes the disparity map using graph cut-based algorithm.
cv.FindStereoCorrespondenceGC(left,right,
                          disparity_left,disparity_right,state)

disp_left_visual = cv.CreateMat(left.height, left.width, cv.CV_8U)
cv.ConvertScale( disparity_left, disp_left_visual, -20 );
cv.Save( "disparity.pgm", disp_left_visual ); # save the map

# cutting the object farthest of a threshold (120)
cut(disp_left_visual,left,120)

cv.NamedWindow('Disparity map', cv.CV_WINDOW_AUTOSIZE)
cv.ShowImage('Disparity map', disp_left_visual)
cv.WaitKey()
예제 #25
0
#!/usr/bin/env python
# -*- coding:utf8 -*-

import cv2

# 读图片
image = cv2.LoadImage('G:/python/opencv_dir/wx.jpg',
                      cv2.CV_LOAD_IMAGE_COLOR)  # Load the image
# Or just: image=cv.LoadImage('img/image.png')

cv2.NamedWindow('a_window', cv2.CV_WINDOW_AUTOSIZE)  # Facultative
cv2.ShowImage('a_window', image)  # Show the image
예제 #26
0
 def __init__(self):
     cv.NamedWindow(color_tracker_window, 1)
     self.capture = cv.CaptureFromCAM(0)
예제 #27
0
	return (pupilImg)

# Returns the image as a "tape" converting polar coord. to Cartesian coord.
#
# @param image		Image with iris and pupil
# @returns image	"Normalized" image
def getPolar2CartImg(image, rad):
	imgSize = cv.GetSize(image)
	c = (float(imgSize[0]/2.0), float(imgSize[1]/2.0))
	imgRes = cv.CreateImage((rad*3, int(360)), 8, 3)
	#cv.LogPolar(image,imgRes,c,50.0, cv.CV_INTER_LINEAR+cv.CV_WARP_FILL_OUTLIERS)
	cv.LogPolar(image,imgRes,c,60.0, cv.CV_INTER_LINEAR+cv.CV_WARP_FILL_OUTLIERS)
	return (imgRes)

# Window creation for showing input, output
cv.NamedWindow("input", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("output", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("normalized", cv.CV_WINDOW_AUTOSIZE)

eyesList = os.listdir('images/eyes')
key = 0
while True:
	eye = getNewEye(eyesList)
	frame = cv.LoadImage("images/eyes/"+eye)
	iris = cv.CloneImage(frame)
	output = getPupil(frame)
	iris = getIris(output)
	cv.ShowImage("input", frame)
	cv.ShowImage("output", iris)
	normImg = cv.CloneImage(iris)
	normImg = getPolar2CartImg(iris,radius)
예제 #28
0
class Target:
    def __init__(self):
        self.capture = cv.CaptureFromCAM(0)

    cv.NamedWindow('Target', 1)
    cv.NamedWindow('Threshold1', 1)
    cv.NamedWindow('Threshold2', 1)
    cv.NamedWindow('hsv', 1)

    def run(self):
        #initiate font
        font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8)
        # instantiate images
        hsv_img = cv.CreateImage(cv.GetSize(cv.QueryFrame(self.capture)), 8, 3)
        threshold_img1 = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
        threshold_img1a = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
        threshold_img2 = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
        i = 0
        writer = cv.CreateVideoWriter('angle_tracking.avi', cv.CV_FOURCC('M', 'J', 'P', 'G'), 30, cv.GetSize(hsv_img), 1)

        while True:
            # capture the image from the cam
            img = cv.QueryFrame(self.capture)

            # convert the image to HSV
            cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV)

            # threshold the image to isolate two colors
            cv.InRangeS(hsv_img, (165, 145, 100), (250, 210, 160), threshold_img1)  # red
            cv.InRangeS(hsv_img, (0, 145, 100), (10, 210, 160), threshold_img1a)  # red again
            cv.Add(threshold_img1, threshold_img1a, threshold_img1)  # this is combining the two limits for red
            cv.InRangeS(hsv_img, (105, 180, 40), (120, 260, 100), threshold_img2)  # blue

            # determine the moments of the two objects
            threshold_img1 = cv.GetMat(threshold_img1)
            threshold_img2 = cv.GetMat(threshold_img2)
            moments1 = cv.Moments(threshold_img1, 0)
            moments2 = cv.Moments(threshold_img2, 0)
            area1 = cv.GetCentralMoment(moments1, 0, 0)
            area2 = cv.GetCentralMoment(moments2, 0, 0)

            # initialize x and y
            x1, y1, x2, y2 = (1, 2, 3, 4)
            coord_list = [x1, y1, x2, y2]
            for x in coord_list:
                x = 0

            # there can be noise in the video so ignore objects with small areas
            if (area1 > 200000):
                # x and y coordinates of the center of the object is found by dividing the 1,0 and 0,1 moments by the area
                x1 = int(cv.GetSpatialMoment(moments1, 1, 0) / area1)
                y1 = int(cv.GetSpatialMoment(moments1, 0, 1) / area1)

            # draw circle
            cv.Circle(img, (x1, y1), 2, (0, 255, 0), 20)

            # write x and y position
            cv.PutText(img, str(x1) +', '+str(y1), (x1, y1 + 20), font, 255)  # Draw the text

            if (area2 > 100000):
                # x and y coordinates of the center of the object is found by dividing the 1,0 and 0,1 moments by the area
                x2 = int(cv.GetSpatialMoment(moments2, 1, 0) / area2)
                y2 = int(cv.GetSpatialMoment(moments2, 0, 1) / area2)

                # draw circle
                cv.Circle(img, (x2, y2), 2, (0, 255, 0), 20)

            cv.PutText(img, str(x2) +', '+str(y2), (x2, y2 + 20), font, 255)  # Draw the text
            cv.Line(img, (x1, y1), (x2, y2), (0, 255, 0), 4, cv.CV_AA)
            # draw line and angle
            cv.Line(img, (x1, y1), (cv.GetSize(img)[0], y1), (100, 100, 100, 100), 4, cv.CV_AA)
            x1 = float(x1)
            y1 = float(y1)
            x2 = float(x2)
            y2 = float(y2)
            angle = int(math.atan((y1 - y2) / (x2 - x1)) * 180 / math.pi)
            cv.PutText(img, str(angle), (int(x1) + 50, (int(y2) + int(y1)) / 2), font, 255)

            # cv.WriteFrame(writer,img)

            # display frames to users
            cv.ShowImage('Target', img)
            cv.ShowImage('Threshold1', threshold_img1)
            cv.ShowImage('Threshold2', threshold_img2)
            cv.ShowImage('hsv', hsv_img)
            # Listen for ESC or ENTER key
            c = cv.WaitKey(7) % 0x100
            if c == 27 or c == 10:
                break
            cv.DestroyAllWindows()
import cv2  #import the openCV lib to python
import serial  #import the pyserial module

#Module -1: Image Processing
hc = cv2.imread(
    '/home/george/PycharmProjects/Embeded image processing system/haarcascade_frontalface_alt2.xml'
)
img = cv2.imshow('/home/jayneil/beautiful-faces.jpg', 0)
faces = cv2.HaarDetectObjects(img, hc, cv2.CreateMemStorage())
a = 1
print(faces)
for (x, y, w, h), n in faces:
    cv2.Rectangle(img, (x, y), (x + w, y + h), 255)
cv2.SaveImage("faces_detected.jpg", img)
dst = cv2.imread('faces_detected.jpg')
cv2.NamedWindow('Face Detected', cv2.CV_WINDOW_AUTOSIZE)
cv2.imshow('Face Detected', dst)
cv2.WaitKey(5000)
cv2.DestroyWindow('Face Detected')

#Module -2: Trigger Pyserial
if faces == []:

    ser = serial.Serial('/dev/ttyUSB0', 9600)
    print(ser)
    ser.write('N')
else:

    ser = serial.Serial('/dev/ttyUSB0', 9600)
    print(ser)
    ser.write('Y')
예제 #30
0
import sys
import cv2
import numpy as np

if (sys.argv[1] == "-i" and len(sys.argv) == 3):
    fileLocation = sys.argv[2]
    img = cv2.imread(fileLocation) 
    
    cv2.imshow("Image", img) 
    cv2.waitkey(0)
    
    cv2.destroyAllWindows()

elif (sys.argv[1] == "-l" and len(sys.argv) == 3):

    cv2.NamedWindow("Camera Feed", cv2.CV_WINDOW_AUTOSIZE)

    port = (int)(sys.argv[2])
    capture = cv2.CaptureFromCAM(port)

    while True:
       frame = cv2.QueryFrame(capture)
       cv2.ShowImage("Camera Feed", frame)

       key = cv2.waitKey(10)
       if key == 27:
           break
    cv2.destroyWindow("Camer Feed")