Exemple #1
0
def environment_correction(cam_xy):
    y = (90, 375)
    x = (561, 30)
    o = (70, 46)
    po = VirtualPosition()
    px = VirtualPosition()
    py = VirtualPosition()
    po.x = o[0]
    po.y = o[1]
    px.x = x[0]
    px.y = x[1]
    py.x = y[0]
    py.y = y[1]
    while True:
        ret, frame = cam_xy.read()
        cv.circle(frame, x, 1, (0, 0, 255), -1)
        cv.circle(frame, y, 1, (0, 0, 255), -1)
        cv.circle(frame, o, 1, (0, 0, 255), -1)
        cv.line(frame, o, x, (255, 255, 0))
        cv.line(frame, o, y, (255, 255, 0))
        cv.imshow('Correction', frame)
        if cv.waitKey(1) & 0xFF == ord('q'):
            cv.destroyWindow('Correction')
            break
    return po, px, py
Exemple #2
0
def mouse_drawing(event, x, y, flags, params):
    if event == cv2.EVENT_LBUTTONDOWN:
        if (buttonSens['text'] == "Vertical"):
            sens = "V"
            if (buttonEntree['text'] == "←Extérieur - Intérieur→"):
                entree = "right"
            else:
                entree = "left"
        else:
            sens = "H"
            if (buttonEntree['text'] == "↑Intérieur\nExtérieur↓"):
                entree = "up"
            else:
                entree = "down"

        if sens == "H":
            toSend.append(y)

        else:
            toSend.append(x)
        toSend.append(sens)
        toSend.append(entree)
        cv2.destroyWindow('Frame')
        videoAnalyse(toSend[0], toSend[1], toSend[2], path[0])
        path.clear()
        toSend.clear()
    """
Exemple #3
0
    def _select_target(self):
        """DOCSTRING"""
        # print('PLACEHOLDER: i, m, or t')

        select_target_message(self.targets)

        win = 'Choose Calibration Target'
        cv2.namedWindow(win)

        cv2.imshow(win, self._circle_draw)

        keypress = -1

        while keypress == -1:
            keypress = cv2.waitKey(5)

        cv2.destroyWindow(win)

        # make this better when you have time
        if keypress == 27:  # ESC
            self._cal_count -= 1
        elif keypress == 113:  # 'q'
            self._cal_count = -1
        else:
            for key in self.targets.keys():
                if chr(keypress) == key[0]:
                    print('\'{0}\' target selected.'.format(key))
                    self.targets[key].calibrate_intrinsic(self._cal_image)
        return
Exemple #4
0
def testLut():
    testimg = cv2.imread('/Users/zjj/Desktop/IMG_3271.jpg')
    lutpath = '/Users/zjj/Desktop/lookup_0_origin_2.png'

    lut = MYLUT(lutpath)
    img = testimg.copy()
    img = lut.imageInLut(img)
    cv2.imwrite('/Users/zjj/Desktop/IMG_3271_lut.jpg', img)
    return 0
    # testimg = cv2.imread('/Users/zjj/Downloads/照片/IMG_0495.JPG')\

    # testimg = cv2.resize(testimg, (600, 400))
    fileinlutdir = os.listdir('lut')
    fileinlutdir = sorted(fileinlutdir)
    for filename in fileinlutdir:
        if filename.endswith('.png') and filename.startswith('lookup'):
            lutpath = 'lut/' + filename
            print('Init', time.time())
            lut = MYLUT(lutpath)
            img = testimg.copy()
            for i in range(1):
                print('Start', time.time())
                img = lut.imageInLut(img)
                print('Finish', time.time())
                windowname = filename + str(i)
                cv2.namedWindow(windowname, cv2.WINDOW_KEEPRATIO)
                cv2.resizeWindow(windowname, 1080, 1920)
                cv2.imshow(windowname, img)
                cv2.waitKey(0)
                cv2.destroyWindow(windowname)
    print("Done")
def stop_video_comm():
    global stop_connection

    stop_connection = True

    #wait for the send thread to close
    try:
        while((thread_send_video !=None) and (thread_send_video.is_alive())):
            print('waiting for send thread to become None')
    except Exception as e:
        print('stopped send thread')

    print('video send thread stopped')

    if((videofeed != None) and (videofeed.capture.isOpened())):
        videofeed.capture.release()
        cv2.destroyWindow(self_username)

    #send CLOSING
    if( client_socket_video_send != None ):
        send('CLOSING')

    try:
        while((thread_listen_video != None) and (thread_listen_video.is_alive())):
            print('waiting for listen thread to become None')
    except Exception as e:
        print('stopped listen thread')

    print('video listen thread stopped')
Exemple #6
0
def faceRecAndVid():

    FRAME_THICKNESS = 2
    FONT_THICKNESS = 1
    MODEL = 'hog'  # Model for recognition cnn/hog
    TOLERANCE = 0.5  # Similarity
    COLOUR = [77, 77, 200]  # shade of red

    # Loads face encodings stored in .dat file
    with open('FaceRecog/Student_Encodings.dat', 'rb') as f:
        Loaded_face_encodings = pickle.load(f)

        face_names = list(Loaded_face_encodings.keys())
        face_encodings = np.array(list(Loaded_face_encodings.values()))
    f.close()

    Student_Names, Student_Face_Encodings = face_names, face_encodings

    video = VideoCapture(0)

    if video is None:
        popUp('Error Getting Video')
    else:
        while True:
            ret, image = video.read()

            if ret == True:
                image = resize(image, (0, 0), None, .75, .75, INTER_AREA)
                image = cv2.flip(
                    image,
                    1)  # not use cv2.rotate(img, deg) / -1 flips it over
                locations = face_recognition.face_locations(image, model=MODEL)
                encodings = face_recognition.face_encodings(image, locations)

                for face_encoding, face_locations in zip(encodings, locations):
                    results = compare_faces(Student_Face_Encodings,
                                            face_encoding, TOLERANCE)
                    match = None

                    if True in results:
                        # match is the name of the identity found
                        match = Student_Names[results.index(True)]
                        Attendance(match)
                        drawBox(image, FRAME_THICKNESS, FONT_THICKNESS, match,
                                face_locations)
                        alertSFX()
                        imshow('Test', image)
                        waitKey(500)

                imshow('Test', image)
                if waitKey(1) & 0xFF == ord("q"):
                    video.release()
                    cv2.destroyWindow('Test')
                    popUp('Done')
                    break
            else:
                video.release()
                popUp('Error getting Video')
                break
Exemple #7
0
 def read(self):
     for i in self.imgs:
         img = cv2.imread(i)  #Read Image
         cv2.imshow(self.ticket_name, img)  #Display Image
         cv2.waitKey(5000)
         cv2.destroyWindow(self.ticket_name)
         print(self.ticket_name)
         print(self.description)
Exemple #8
0
def adjust_circle(image, circle):
    """Manually adjust a circle on an image.  Takes an input image and
    circle(center, radius) and shows a blown up region centered around the
    circle.  Allows the user to adjust the circle using trackbars.  Waits
    for keypress to finish.  Returns adjusted circle and keypress."""

    # initialize window and trackbars
    win = 'Adjust Target Circle'
    cv2.namedWindow(win)
    cv2.resizeWindow(win, 200, 200)

    # initialize variables
    roi, roi_origin = get_circle_roi(image, circle)

    circle_local = np.copy(circle)
    circle_local[0] = circle[0] - np.flipud(roi_origin)

    # scale image to be bigger and allow for easier adjustment
    scale = cf['roi']['ADJUST_SCALE']
    roi = scale_image(roi, scale)
    circle_local = np.multiply(circle_local, scale)

    img_circ = np.copy(roi)
    # Set max radius of circle such that the max diameter is the length
    # of the region of interest
    max_radius = roi.shape[0] // 2

    # initialize trackbars
    cv2.createTrackbar('x', win,
                       circle_local[0][0], roi.shape[1], empty_callback)
    cv2.createTrackbar('y', win,
                       circle_local[0][1], roi.shape[0], empty_callback)
    cv2.createTrackbar('r', win,
                       circle_local[1], max_radius, empty_callback)

    keypress = -1

    while keypress == -1:
        cv2.circle(img_circ,
                   (cv2.getTrackbarPos('x', win),
                    cv2.getTrackbarPos('y', win)),
                   cv2.getTrackbarPos('r', win),
                   (0, 0, 0),
                   1)
        cv2.imshow(win, img_circ)
        img_circ = np.copy(roi)
        keypress = cv2.waitKey(5)

    adj_circle = ((cv2.getTrackbarPos('x', win) // scale +
                   roi_origin[1],
                   cv2.getTrackbarPos('y', win) // scale +
                   roi_origin[0]),
                  cv2.getTrackbarPos('r', win) // scale)

    cv2.destroyWindow(win)
    return adj_circle, keypress
Exemple #9
0
def testBlur():
    img = cv2.imread('resource/one1.png')
    for ang in range(-360, 360, 15):
        kernel = blurKernel(length=20, angle=ang)
        motion_blur = cv2.filter2D(img, -1, kernel)
        # blur = cv2.GaussianBlur()
        winname = 'test motion {}'.format(ang)
        cv2.imshow(winname, motion_blur)
        cv2.waitKey(0)
        cv2.destroyWindow(winname)
 def show(self, color=(0, 0, 255), thickness=3):
     """
     显示结果
     :param color: 边框颜色
     :param thickness: 边框粗细
     :return :
     """
     cv2.imshow("Color Block", self.draw_contours(color=color, thickness=thickness))
     cv2.waitKey()
     cv2.destroyWindow("Color Block")
Exemple #11
0
    def generate(self):
        while True:
            open_cv.imshow(self.caption, self.image)
            key = open_cv.waitKey(0)

            if key == CoordinatesGenerator.KEY_RESET:
                self.image = self.image.copy()
            elif key == CoordinatesGenerator.KEY_QUIT:
                break
        open_cv.destroyWindow(self.caption)
Exemple #12
0
def tune_thresholds(vid_feed, thresholds):
    """DOCSTRING"""
    # initialize window
    win = 'Adjustment Control Panel'
    cv2.namedWindow(win)

    # initialize variables and trackbars
    thresh_names = ['H_LO', 'H_HI',
                    'S_LO', 'S_HI',
                    'V_LO', 'V_HI']

    blur_k_name = 'BLUR \'K\''

    max_vals = [179, 179, 255, 255, 255, 255]

    for thresh, val, max_val in zip(thresh_names,
                                    thresholds,
                                    max_vals):
        cv2.createTrackbar(thresh, win, val, max_val, empty_callback)

    cv2.createTrackbar(blur_k_name, win,
                       cf['blur_k']['initial'],
                       cf['blur_k']['max'],
                       empty_callback)
    cv2.setTrackbarMin(blur_k_name, win, 1)

    thresh_vals = None
    keypress = -1

    while keypress == -1:
        __, frame = vid_feed.read()

        # blur frame
        blur_k = cv2.getTrackbarPos(blur_k_name, win)
        frame_blur = cv2.blur(frame, (blur_k, blur_k))

        frame_hsv = cv2.cvtColor(frame_blur, cv2.COLOR_BGR2HSV)

        thresh_vals = np.asarray([cv2.getTrackbarPos(name, win)
                                  for name in thresh_names])

        frame_thresh = cv2.inRange(frame_hsv,
                                   thresh_vals[::2],
                                   thresh_vals[1::2])

        # cv2.imshow(win_thresh, frame_thresh)
        cv2.imshow(win, frame_thresh)

        keypress = cv2.waitKey(5)

    cv2.destroyWindow(win)
    vid_feed.release()
    return thresh_vals, keypress
Exemple #13
0
    def update(self):
        #creates new image
        cv2.namedWindow(self.ticket_name)  # names our camera window
        vc = cv2.VideoCapture(0)  #looks at first frame

        #detects if the camera is on or not
        if vc.isOpened():
            rval, frame = vc.read()  # Shows camera feed
        else:
            rval = False

        while rval:  # keeps camera on
            cv2.imshow(self.ticket_name, frame)  # shows camera feed
            rval, frame = vc.read()  # shows camera feed
            frame = cv2.flip(frame, 1)  # inverts camera
            key = cv2.waitKey(
                20
            )  # sets keyboard commands later, but here it waits 20ms for each frame
            if key == 27:  # exit on ESC - this is an emergancy exit
                break
            elif key % 256 == 32:  # SPACE pressed - takes a picture!
                self.new_img = "pics/after_{}.png".format(
                    self.img_counter)  # writes file name, in pics path
                cv2.imread(self.new_img,
                           1)  # shows us tour picture *sometimes late*
                cv2.imwrite(self.new_img, frame)  # creates img file
                print("{} written!".format(
                    self.new_img))  #terminal output to help us
                rval = False

        vc.release()  # stops capturing images
        cv2.destroyWindow(self.ticket_name)  # destroys cv2 window

        #combineds images thanks to https://answers.opencv.org/question/175912/how-to-display-multiple-images-in-one-window/
        before = cv2.imread(self.img_name)  #opens images
        after = cv2.imread(self.new_img)

        #breaks code, meant to resize images
        # before = cv2.resize(self.img_name,None,fx=0.5,fy=0.95) #resizes imgs
        # after = cv2.resize(self.new_img,None,fx=0.5,fy=0.95)

        numpy_horizontal_concat = np.concatenate((before, after),
                                                 axis=1)  #sorts the row
        cv2.imwrite(self.img_name, numpy_horizontal_concat)
        cv2.imshow(self.ticket_name + " *Cleaned!*", numpy_horizontal_concat)

        cv2.waitKey(5000)
        cv2.destroyWindow(self.ticket_name)

        #makes final changes
        self.ticket_name += " *Cleaned!* "
        self.description += " *Post Description* "
        self.description += input("Clean up description: ")
 def show(self):
     # 显示窗口
     win_name = 'CvGui'
     cv2.namedWindow(win_name, cv2.WINDOW_AUTOSIZE)
     cv2.setMouseCallback(win_name, self.on_mouse)
     key = None
     while True:
         cv2.imshow(win_name, self.display)
         key = cv2.waitKey(50)
         if key == 27:
             # ESC,退出
             break
         self.render()
     cv2.destroyWindow(win_name)
def camPreview(previewName, camID):
    cv2.namedWindow(previewName)
    cam = cv2.VideoCapture(camID, cv2.CAP_DSHOW)
    if cam.isOpened():  # try to get the first frame
        rval, frame = cam.read()
    else:
        rval = False

    while rval:
        cv2.imshow(previewName, frame)
        rval, frame = cam.read()
        key = cv2.waitKey(20)
        if key == 27:  # exit on ESC
            break
    cv2.destroyWindow(previewName)
Exemple #16
0
def drag_circle(image):
    """Displays input image and lets user draw a circle by dragging the
    mouse from the center to the edge.  Waits for keypress to finish.
    Returns circle parameters(center, radius) and keypress.
    """

    # initialize window
    win = 'Select Calibration Region'
    cv2.namedWindow(win)

    # initialize variables
    cb_params = {'drag': None,
                 'point1': np.zeros(2),
                 'point2': np.zeros(2),
                 'released': False}
    center = None
    radius = None
    keypress = -1

    cv2.imshow(win, image)

    while keypress == -1:

        # mouse callback function for dragging circle on window
        cv2.setMouseCallback(win, circle_mouse_callback,
                             param=cb_params)

        center = cb_params['point1']
        radius = np.int(np.linalg.norm(cb_params['point1'] -
                                       cb_params['point2']))

        # continuously draw circle on image while mouse is being dragged
        if cb_params['drag'] or cb_params['released']:
            circ_img = image.copy()
            cv2.circle(circ_img,
                       tuple(center),
                       radius,
                       (0, 0, 0), 1, 8, 0)
            cv2.imshow(win, circ_img)

        keypress = cv2.waitKey(5)

    circle = [center, radius]

    cv2.destroyWindow(win)
    return circle, keypress
Exemple #17
0
    def run(self):
        escape = False  # Flag to quit program
        # Let's create our working window and set a mouse callback to handle events
        cv2.namedWindow(self.window_name, flags=cv2.WINDOW_AUTOSIZE)
        #cv2.imshow(self.window_name, np.zeros(CANVAS_SIZE, np.uint8))

        frame = cv2.imread(basic_img)
        frame = frame[y:y + h, x:x + w]  # crop image
        cv2.imshow(self.window_name, frame)
        cv2.waitKey(1)
        cv2.setMouseCallback(self.window_name, self.on_mouse)

        while not escape:

            # This is our drawing loop, we just continuously draw new images
            # and show them in the named window
            frame = cv2.imread(basic_img)
            frame = frame[y:y + h, x:x + w]  # crop image
            canvas = frame
            if len(self.points) > 0:
                # Draw all the current polygon segments
                cv2.polylines(canvas, np.array([self.points]), False,
                              FINAL_LINE_COLOR, 3)
                # And also show what the current segment would look like
                cv2.line(canvas, self.points[-1], self.current,
                         WORKING_LINE_COLOR, 3)

            for i in range(len(polygon_points)):
                if len(polygon_points[i]) > 0:
                    cv2.fillPoly(canvas, np.array([polygon_points[i]]),
                                 FINAL_LINE_COLOR)

            # Update the window
            cv2.imshow(self.window_name, canvas)
            # And wait 50ms before next iteration (this will pump window messages meanwhile)
            if cv2.waitKey(50) == 27:  # ESC hit
                # todo: maybe add txt export here
                self.done = True
                escape = True

        # Waiting for the user to press any key
        cv2.waitKey()

        cv2.destroyWindow(self.window_name)
        return canvas
def process_unknown_faces(path):
    print('Processing unknown faces...')
    for filename in os.listdir(path):
        # Load image
        print(f'Filename {filename}', end='')
        image = face_recognition.load_image_file(f'{path}/{filename}')

        locations = face_recognition.face_locations(image, model=MODEL)

        encodings = face_recognition.face_encodings(image, locations)

        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        print(f', found {len(encodings)} face(s)')
        for face_encoding, face_location in zip(encodings, locations):

            results = face_recognition.compare_faces(known_faces,
                                                     face_encoding, TOLERANCE)

            match = None
            if True in results:  # If at least one is true, get a name of first of found labels
                match = known_names[results.index(True)]
                print(f"Match found! {match}")

                top_left = (face_location[3], face_location[0])
                bottom_right = (face_location[1], face_location[2])

                color = [0, 255, 0]

                cv2.rectangle(image, top_left, bottom_right, color,
                              FRAME_THICKNESS)

                top_left = (face_location[3], face_location[2])
                bottom_right = (face_location[1], face_location[2] + 22)

                cv2.rectangle(image, top_left, bottom_right, color, cv2.FILLED)
                cv2.putText(image, match,
                            (face_location[3] + 10, face_location[2] + 15),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200),
                            FONT_THICKNESS)

        # Show image
        cv2.imshow(filename, image)
        cv2.waitKey(0)
        cv2.destroyWindow(filename)
Exemple #19
0
    def create(self):
        cv2.namedWindow(self.ticket_name)  # names our camera window
        vc = cv2.VideoCapture(0)  #looks at first frame

        #detects if the camera is on or not
        if vc.isOpened():
            rval, frame = vc.read()  # Shows camera feed
        else:
            rval = False

        while rval:  # keeps camera on
            cv2.imshow(self.ticket_name, frame)  # shows camera feed
            rval, frame = vc.read()  # shows camera feed
            frame = cv2.flip(frame, 1)  # inverts camera
            key = cv2.waitKey(
                20
            )  # sets keyboard commands later, but here it waits 20ms for each frame
            if key == 27:  # exit on ESC - this is an emergancy exit
                break
            elif key % 256 == 32:  # SPACE pressed - takes a picture!
                self.img_name = "pics/ticket_{}.png".format(
                    self.img_counter)  # writes file name, in pics path
                cv2.imread(self.img_name,
                           1)  # shows us tour picture *sometimes late*
                cv2.imwrite(self.img_name, frame)  # creates img file
                print("{} written!".format(
                    self.img_name))  #terminal output to help us
                self.img_counter += 1  # helps name imgs
                rval = False

        vc.release()  # stops capturing images
        cv2.destroyWindow(self.ticket_name)  # destroys cv2 window
        self.ticket_name = input("Name of Ticket: ")
        self.description = input("Location and Description: ")
        self.imgs.append(self.img_name)

        #access cancle method to determine if user wants to save or not
        while True:
            save = input("Would you like to save?(y/n): ")
            if save == 'y':
                return False
            elif save == 'n':
                self.cancle()
                return False
def see_img_shape( directory, is_array = True, frame_name= 'frame'):
	"""
	INPUT:\n
	directory is the string that contains the directory of image\n
	if already loaded then pass True in is_array.\n
	OUTPUT:\n
	Image in another window\n
	INSTRUCTIONS:\n
	Press any key to close image\n
	"""
	if not is_array:
		img = cv2.imread( directory, 1)
	else:
		img = directory
	print( img.shape)

	cv2.imshow( frame_name, img)
	cv2.waitKey( 0)
	cv2.destroyWindow( frame_name)
	return None
Exemple #21
0
def showScreenImg(fileName):
    imagePath = "./lib/{}.png".format(fileName)
    img = cv.imread(imagePath)
    height, width, _ = img.shape
    resizedImg = cv.resize(img, (width // resize, height // resize))
    cv.namedWindow('screen')
    cv.setMouseCallback('screen', saveTapPos, resizedImg)
    while 1:
        cv.imshow("screen", resizedImg)
        k = cv.waitKey(1)
        if k == 27:
            cv.destroyWindow('screen')
            break
    if screenImgNum > touchTimes:
        start()
    elif screenImgNum == 1:
        time.sleep(1)
        touchHandler(addMsgPos[0][0], addMsgPos[0][1])
    else:
        getScreen("msgScreen{}".format(screenImgNum))
Exemple #22
0
def acquire_images(cam, save_queue: queue.Queue) -> None:
    cv2.namedWindow(WINDOW_NAME)
    cv2.moveWindow(WINDOW_NAME, 0, 0)
    cam.AcquisitionMode.SetValue(PySpin.AcquisitionMode_Continuous)
    cam.BeginAcquisition()
    print("Acquisition started.")
    print("Press enter to save images. Press escape to exit.")

    pixel_format = cam.PixelFormat.GetCurrentEntry().GetSymbolic()

    while True:
        retrieved_image = get_newest_image(cam, pixel_format)
        if retrieved_image is None:
            break

        cv2.imshow(
            WINDOW_NAME,
            retrieved_image.get_resized_image(flags.FLAGS.display_width),
        )
        keypress = cv2.waitKey(1)

        if keypress == 27:
            # escape key pressed
            break
        elif cv2.getWindowProperty(WINDOW_NAME, cv2.WND_PROP_VISIBLE) < 1:
            # x button clicked
            break
        elif keypress == 13:
            # Enter key pressed
            cv2.imshow(
                WINDOW_NAME,
                retrieved_image.get_highlighted_image(
                    flags.FLAGS.display_width),
            )
            save_queue.put(retrieved_image)
            cv2.waitKey(500)

    save_queue.put(None)
    cv2.destroyWindow(WINDOW_NAME)
    cam.EndAcquisition()
    print("Acquisition Ended.")
Exemple #23
0
def capture_targets(vid_feed):
    """Displays video from input feed and waits for a keypress to capture an
    image.  Returns captured image and keypress.
    """

    # initialize window
    win = 'Camera Feed'
    cv2.namedWindow(win)
    focus_window(win)

    # initialize variables
    image = None
    keypress = -1

    while keypress == -1:
        __, image = vid_feed.read()
        cv2.imshow(win, image)
        keypress = cv2.waitKey(10)

    cv2.destroyWindow(win)
    return image, keypress
Exemple #24
0
def show_cv_image(images, title='image'):
    """show a opencv2 window that can be destroyed with any key.

    this will only work if the images are all of the same size.

    :param img: images to show
    :type img: list[cv2 image]
    :param title: title of the window to create, defaults to 'image'
    :type title: string
    """
    # if images is not a list make it one
    if type(images) is not list:
        images = [images]

    # check if the list is greater than 1 and concat the images for opencv
    if len(images) > 1:
        cv2.imshow(title, np.hstack(images))
    else:
        cv2.imshow(title, images[0])
    cv2.waitKey(0)
    cv2.destroyWindow(title)
Exemple #25
0
    def GetFeed(self) -> None:
        try:
            cv2.namedWindow("preview")

            if self.vc.isOpened():
                rval, frame = self.vc.read()
            else:
                rval = False

            while rval:
                cv2.imshow("preview", frame)
                rval, frame = self.vc.read()
                key = cv2.waitKey(20)
                if key == 27:  # exit on ESC
                    break

            self.CloseCamera()
            cv2.destroyWindow("preview")

        finally:
            self.CloseCamera()
Exemple #26
0
def testImages():
    frame1 = cv2.imread('resource/fly1.jpg')
    frame2 = cv2.imread('resource/fly2.jpg')
    # res = motionBlurWithFrames(frame1, frame2)
    # cv2.imshow('blr', res)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    # test
    imgsize = (1920, 1080)
    frame1 = cv2.resize(frame1, imgsize)
    frame2 = cv2.resize(frame2, imgsize)
    # res = flowLucasWithFrames(frame1, frame2)
    res = flowFarnebackWithFrames(frame1, frame2, fps=30)
    # res = simpleAddWithFrames(frame1, frame2)

    name = 'blur'
    cv2.namedWindow(name, cv2.WINDOW_NORMAL)
    # cv2.resizeWindow(name, 640, 480)
    cv2.imshow(name, res)
    cv2.waitKey(0)
    cv2.destroyWindow(name)
Exemple #27
0
def webcam_face_recognizer(database):
    """
    Runs a loop that extracts images from the computer's webcam and determines whether or not
    it contains the face of a person in our database.

    If it contains a face, an audio message will be played welcoming the user.
    If not, the program will process the next frame from the webcam
    """
    global ready_to_detect_identity

    cv2.namedWindow("preview")
    vc = cv2.VideoCapture(0)

    face_cascade = cv2.CascadeClassifier(
        os.path.join(haarcascades, 'haarcascade_frontalface_default.xml'))
    face_detector = cv2.CascadeClassifier(
        os.path.join(haarcascades, 'haarcascade_frontalface_alt.xml'))
    open_eyes_detector = cv2.CascadeClassifier(
        os.path.join(haarcascades, 'haarcascade_eye_tree_eyeglasses.xml'))
    left_eye_detector = cv2.CascadeClassifier(
        os.path.join(haarcascades, 'haarcascade_lefteye_2splits.xml'))
    right_eye_detector = cv2.CascadeClassifier(
        os.path.join(haarcascades, 'haarcascade_righteye_2splits.xml'))

    while vc.isOpened():
        _, frame = vc.read()
        img = frame

        # We do not want to detect a new identity while the program is in the process of identifying another person
        if ready_to_detect_identity:
            img = process_frame(img, frame, face_cascade, open_eyes_detector,
                                left_eye_detector, right_eye_detector)

        key = cv2.waitKey(100)
        cv2.imshow("preview", img)

        if key == 27:  # exit on ESC
            break
    cv2.destroyWindow("preview")
Exemple #28
0
def scan_code(user_profile) -> set or None:
    """
    Scan the barcode and check user restrictions using helper functions.

    :param user_profile: profile of the current user.
    :return: set containing label requirements which are not met.
    """
    cap_device = cv2.VideoCapture(0, cv2.CAP_DSHOW)

    while True:
        _, frame = cap_device.read()

        decoded_objects = pyzbar.decode(frame)

        cv2.imshow("Frame", frame)

        cv2.waitKey(1)
        if decoded_objects:
            labels = set(find_labels(user_profile))
            destroyWindow("Frame")
            cap_device.release()
            return match_labels(labels, decoded_objects[0].data)
Exemple #29
0
def acquire_images(cam, save_queue: queue.Queue) -> None:
    cv2.namedWindow(WINDOW_NAME)
    cv2.moveWindow(WINDOW_NAME, 0, 0)

    cam.start_image_acquisition()
    print("Acquisition started.")
    print("Press enter to save images. Press escape to exit.")
    while True:
        retrieved_image = get_newest_image(cam)
        if retrieved_image is None:
            break

        cv2.imshow(
            WINDOW_NAME,
            retrieved_image.get_resized_image(flags.FLAGS.display_width),
        )
        keypress = cv2.waitKey(1)

        if keypress == 27:
            # escape key pressed
            break
        elif cv2.getWindowProperty(WINDOW_NAME, cv2.WND_PROP_VISIBLE) < 1:
            # x button clicked
            break
        elif keypress == 13:
            # Enter key pressed
            cv2.imshow(
                WINDOW_NAME,
                retrieved_image.get_highlighted_image(
                    flags.FLAGS.display_width),
            )
            save_queue.put(retrieved_image)
            cv2.waitKey(500)

    save_queue.put(None)
    cv2.destroyWindow(WINDOW_NAME)
    cam.stop_image_acquisition()
    print("Acquisition Ended.")
Exemple #30
0
    def start(self):
        """
        对一个当前位置来说,这个位置应该与哪个目标点进行比较?
        """

        cap = cv2.VideoCapture(2)
        if not cap.isOpened():
            print("Cannot open camera")
            exit()

        self.output_serial()

        # count = 300
        # while not self.route.is_finish() and count > 0:
        while not self.route.is_finish():
            # count -= 1
            ret, frame = cap.read()
            if not ret:
                print("Can't receive frame (stream end?). Exiting ...")
                cap.release()
                cv2.destroyWindow(self.name)
                break
            frame = cv2.resize(frame, (cfg.image_width, cfg.image_height),
                               interpolation=cv2.INTER_AREA)
            self.current_loc = self.location.get_cur_loc(frame)
            self.get_next_destionation()
            self.paint_delta(frame)
            print(self.compute_delta())
            if cv2.waitKey(100) & 0xFF == 27:
                print('Interrupt!')
                cv2.destroyWindow(self.name)
                return
        print('Done!')
        cv2.waitKey()
        cv2.destroyWindow(self.name)
        return


# controller = Controller('images/origin.png', 'images/path/path1-1.png', 'jsons/path1-1.json')
# controller.start()