Exemplo n.º 1
0
def main():
    """
    Main function to handle OpenCV windows and neural engine
    """
    # link openCV canvas with drawing GUI callback
    canvas = DrawingGUI()
    cv2.namedWindow('imageDetector')
    cv2.setMouseCallback('imageDetector', canvas.lineDrawing)

    tf.compat.v1.logging.set_verbosity(
        tf.compat.v1.logging.ERROR)  # disable TF optimization warnings
    c = testModel.HandwritingClassifier()
    showInstructions()

    # runs while window is open
    while cv2.getWindowProperty('imageDetector', cv2.WND_PROP_VISIBLE) > 0:
        cv2.imshow('imageDetector', canvas.img)
        key = cv2.waitKey(33)
        if key == ESC_KEY:
            break
        elif key == Q_KEY:
            canvas.clearCanvas()
        elif key == E_KEY:
            canvas.toggleEraser()
        elif key == SPACE_KEY:
            # run neural network on current canvas
            predictions = c.predict(canvas.getResizedImg())[:2]
            print()
            [
                print('{:15} Confidence: {:.5f}'.format(
                    letter, round(prob, 5))) for letter, prob in predictions
            ]
            print()
    cv2.destroyAllWindows()
Exemplo n.º 2
0
def start_cameras(camera_id=0):
    left_camera = CSI_Camera()
    left_camera.open(
        gstreamer_pipeline(
            sensor_id=camera_id,
            sensor_mode=3,
            flip_method=0,
            display_height=540,
            display_width=960,
        ))
    left_camera.start()

    right_camera = CSI_Camera()
    right_camera.open(
        gstreamer_pipeline(
            sensor_id=camera_id,
            sensor_mode=3,
            flip_method=0,
            display_height=540,
            display_width=960,
        ))
    right_camera.start()

    cv.namedWindow("CSI Cameras", cv.WINDOW_AUTOSIZE)

    if (not left_camera.video_capture.isOpened()
            or not right_camera.video_capture.isOpened()):
        # Cameras did not open, or no camera attached

        print("Unable to open any cameras")
        # TODO: Proper Cleanup
        SystemExit(0)

    while cv.getWindowProperty("CSI Cameras", 0) >= 0:

        _, left_image = left_camera.read()
        _, right_image = right_camera.read()
        camera_images = np.hstack((left_image, right_image))
        cv.imshow("CSI Cameras", camera_images)

        # This also acts as
        keyCode = cv.waitKey(30) & 0xFF
        # Stop the program on the ESC key
        if keyCode == 27:
            break

    left_camera.stop()
    left_camera.release()
    right_camera.stop()
    right_camera.release()
    cv.destroyAllWindows()
Exemplo n.º 3
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.")
Exemplo n.º 4
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.")
def get_image_roi(rgb_image):
    '''
    获得用户ROI区域的rect=[x,y,w,h]
    :param rgb_image:
    :return:
    '''
    #    bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
    global g_rect
    img = rgb_image
    cv2.namedWindow('image')
    cv2.resizeWindow('image', 640, 480)
    while True:
        cv2.setMouseCallback('image', on_mouse)
        cv2.resizeWindow('image', 640, 480)
        cv2.startWindowThread()  # 加在这个位置
        cv2.imshow('image', img)
        key = cv2.waitKey(0)
        if cv2.getWindowProperty('image', cv2.WND_PROP_AUTOSIZE) < 1:
            break

    cv2.destroyAllWindows()
    #    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return g_rect
    while screen_capture.is_alive():
        try:
            # get the image from the queue that is put in by ScreenCapture
            img = img_queue.get_nowait()
            # show the image in the Porthole
            cv.imshow('Porthole', img)

            # get the location of the black square on the Viewport window
            w_left, w_top, w_width, w_height = cv.getWindowImageRect(viewport)
            # convert and limit
            bbox = screen_capture.image_rect_to_bbox(w_left, w_top, w_width,
                                                     w_height)
            left, upper, right, lower = screen_capture.limit_bbox_to_monitor(
                bbox, mon_width, mon_height)
            # apply to the shared array
            monitor[:] = (left, upper, right, lower)

            if not bool(cv.getWindowProperty(viewport, cv.WND_PROP_VISIBLE)):
                break  # if the Viewport is closed
            if cv.waitKey(1) & 0xFF == ord("q"):
                break  # if Q is pressed
        except Empty:
            continue
        except KeyboardInterrupt:
            break

    # clean up
    cv.destroyAllWindows()
    screen_capture.stop()
    screen_capture.join()
Exemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser(
        description="combine two images with an arrow in between. Spacing and color is automatically decided and is meant to be nice"
    )

    parser.add_argument(
        "image_file_1", action="store", type=str, help="the image file in the left"
    )
    parser.add_argument(
        "image_file_2", action="store", type=str, help="the image file in the right"
    )
    parser.add_argument(
        "--output",
        "-o",
        action="store",
        required=False,
        type=str,
        help="the output image file. (e.g. out.jpg out.png) If omitted, <img1>-<img2>.png will be generated under current directory",
    )

    parser.add_argument(
        "--scale",
        "-s",
        required=False,
        default=1.0,
        action="store",
        type=float,
        help="the scale of the generated image, 1 for no scaling. 0.5 for half the size, etc",
    )

    argv = parser.parse_args()

    img1 = cv2.imread(argv.image_file_1, 1)
    img2 = cv2.imread(argv.image_file_2, 1)

    s_height = min(img1.shape[0], img2.shape[0])
    b_height = max(img1.shape[0], img2.shape[0])

    s_width = min(img1.shape[1], img2.shape[1])
    b_width = max(img1.shape[1], img2.shape[1])

    frame = np.full((b_height, 2 * s_width + b_width, 3), 255, dtype=np.uint8)

    place_on_top(img1, frame, [(b_height - img1.shape[0]) // 2, 0])
    place_on_top(
        img2, frame, [(b_height - img2.shape[0]) // 2, s_width + img1.shape[1]]
    )

    m1 = cv2.mean(img1)
    m2 = cv2.mean(img2)

    mean_color = []
    for i in range(3):
        mean_color.append(int(m1[i] + m2[i]) // 2)

    cv2.arrowedLine(
        frame,
        (img1.shape[1] + s_width // 5, b_height // 2),
        (img1.shape[1] + s_width - s_width // 5, b_height // 2),
        mean_color,
        8,
        tipLength=0.6,
    )

    assert argv.scale > 0, "scale has to be a positive float"
    frame = cv2.resize(
        frame, (int(frame.shape[1] * argv.scale), int(frame.shape[0] * argv.scale))
    )

    outname = argv.output
    if argv.output is not None:
        try:
            cv2.imwrite(argv.output, frame)
        except cv2.error as e:
            print(e, file=stderr)
            print("Failed to save the image")
            print("Did you forget to specify image format to the output file?")
    else:
        default_name = (
            path.splitext(path.basename(argv.image_file_1))[0]
            + "-"
            + path.splitext(path.basename(argv.image_file_2))[0]
            + ".png"
        )
        outname = default_name
        cv2.imwrite(default_name, frame)

    cv2.imshow(outname, frame)
    while cv2.getWindowProperty(outname, cv2.WND_PROP_VISIBLE) == 1:
        if cv2.waitKey(50) != -1:
            break

    cv2.destroyAllWindows()
def trace_ROI(App):
    global parameters, i, drawingROI, drawingCL, selectedLine, ROImask, ROI, cut_lines

    def updateSTrackbar(value):
        global i
        i = value
        return

    def initialize_mask(parameters):
        # global parameters
        # Compute the ROI mask once to keep it in memory
        roi_norm_str = eval(str(parameters['ROI']))
        if roi_norm_str:
            roi_norm = np.asarray(roi_norm_str)
            roi = (roi_norm * [
                parameters['Width_Image'], parameters['Height_Image']
            ]).astype(int)  # scale ROI with image size, round to nearest pixel
            roi_mask = np.zeros(
                (parameters['Height_Image'], parameters['Width_Image']),
                dtype=np.uint8)
            ROI_mask = cv2.drawContours(image=roi_mask,
                                        contours=[roi],
                                        contourIdx=0,
                                        color=(255, 255, 255),
                                        thickness=-1)
        else:
            roi = np.array([[0, 0]], dtype=np.int32)  # ROI contour
            ROI_mask = np.ones(
                (parameters['Height_Image'], parameters['Width_Image']),
                dtype=np.uint8)

        return roi, ROI_mask

    def initialize_cut_line(parameters):
        # Builds the cut_lines array from the parameters
        # Cut line specified in the parameters file in normalized coordinates
        # (x1,y1), (x2,y2): read in, scale into image coordinates

        # Get all parameter fields that begin with 'cutLine
        cutline_keys = fnmatch.filter(parameters.keys(), 'Cut_Line*')
        cut_lines = []
        for key in cutline_keys:
            cutLine_norm_str = eval(str(parameters[key]))
            if cutLine_norm_str:
                cutLine_norm = np.asarray(cutLine_norm_str)
                cutLine = (cutLine_norm * [
                    parameters['Width_Image'], parameters['Height_Image']
                ]).astype(
                    int
                )  # scale cut line with image size, round to nearest pixel
            else:
                cutLine = np.array([[0, 0]],
                                   dtype=np.int32)  # default cut line
            cut_lines.append(cutLine)
        return cut_lines

    def selectLine(event, x, y, flags, params):
        global drawingROI, drawingCL, selectedLine, ROI, ROImask, cut_lines, parameters
        if mode == 'ROI':
            if drawingROI:
                ROI[-1] = [x, y]
            if event == cv2.EVENT_LBUTTONDOWN:  # Left click
                if not drawingROI:
                    ROI = np.array([[0, 0]], dtype=np.int32)
                    ROI[-1] = [x, y]
                    drawingROI = True
                ROI = np.append(ROI, [[x, y]], axis=0)

            if event == cv2.EVENT_RBUTTONDOWN:  # Right click
                # print('ROI (absolu) : \n{}\n'.format([[couple[0],couple[1]] for couple in ROI]))
                ROI_rel = np.zeros_like(ROI, dtype=float)
                ROI_rel[:,
                        0] = np.around(ROI[:, 0] / parameters['Width_Image'],
                                       decimals=2)
                ROI_rel[:,
                        1] = np.around(ROI[:, 1] / parameters['Height_Image'],
                                       decimals=2)
                strInfo = 'ROI : {}'.format([[couple[0], couple[1]]
                                             for couple in ROI_rel])
                print(strInfo + '\n')
                try:
                    App.Info.set(strInfo)
                except:
                    pass
                drawingROI = False
                ROImask = np.zeros(
                    (parameters['Height_Image'], parameters['Width_Image']),
                    dtype=np.uint8)
                cv2.drawContours(ROImask, [ROI], 0, (255, 255, 255), -1)
                parameters['ROI'] = str([[couple[0], couple[1]]
                                         for couple in ROI_rel])  # + '\n'

        if mode == 'CL':
            if drawingCL:
                cut_lines[selectedLine - 1][-1] = [x, y]
            if event == cv2.EVENT_LBUTTONDOWN:  # Left click
                if not drawingCL:
                    cut_lines[selectedLine - 1] = np.array([[0, 0]],
                                                           dtype=np.int32)
                    cut_lines[selectedLine - 1][-1] = [x, y]
                    drawingCL = True
                cut_lines[selectedLine - 1] = np.append(
                    cut_lines[selectedLine - 1], [[x, y]], axis=0)

            if event == cv2.EVENT_RBUTTONDOWN:
                # print('Ligne de coupe (absolu) : \n{}\n'.format([[couple[0],couple[1]] for couple in cut_line]))
                cut_lineRel = np.zeros_like(cut_lines[selectedLine - 1],
                                            dtype=float)
                cut_lineRel[:,
                            0] = np.around(cut_lines[selectedLine - 1][:, 0] /
                                           parameters['Width_Image'],
                                           decimals=2)
                cut_lineRel[:,
                            1] = np.around(cut_lines[selectedLine - 1][:, 1] /
                                           parameters['Height_Image'],
                                           decimals=2)
                strInfo = 'Ligne de coupe #{} : {}'.format(
                    selectedLine,
                    [[couple[0], couple[1]] for couple in cut_lineRel])
                print(strInfo + '\n')
                try:
                    App.Info.set(strInfo)
                except:
                    pass
                drawingCL = False
                parameters['Cut_Line' + str(selectedLine)] = str(
                    [[couple[0], couple[1]]
                     for couple in cut_lineRel])  # + '\n'

    drawingROI = False  # Tracé du ROI en cours
    drawingCL = False  # Tracé de la Cut Line en cours
    selectedLine = 0  # CutLine selected
    mode = 'ROI'  # 'ROI' ou 'CL'
    showHelp = True
    lineColors = [(0, 0, 255), (255, 0, 0), (0, 255, 0),
                  (255, 0, 255)]  # Red / Blue / Green / Violet

    parameters = App.parameters.copy()
    try:
        videoPath = App.VideoPath.get()
        excelPath = App.ExcelPath.get()
    except:
        videoPath = App.VideoPath
        excelPath = App.ExcelPath

    cap = cv2.VideoCapture(videoPath)

    time.sleep(0.5)
    if not cap.isOpened():
        strInfo = 'Impossible d\'ouvrir : {}'.format(videoPath)
        print(strInfo)
        try:
            App.Info.set(strInfo)
        except:
            pass
        return

    tots = cap.get(
        cv2.CAP_PROP_FRAME_COUNT)  # Set to a negative number for streaming
    parameters['Width_Image'] = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    parameters['Height_Image'] = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    cv2.namedWindow('Video Player', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('Video Player', parameters['Width_Image'],
                     parameters['Height_Image'])
    cv2.moveWindow('Video Player', 50, 50)
    if tots > 0:
        cv2.createTrackbar('S', 'Video Player', 0,
                           int(tots) - 1, updateSTrackbar)

    cv2.setMouseCallback('Video Player', selectLine)

    status = 'play'
    isRunning = True
    i = 1

    cut_lines = initialize_cut_line(parameters)
    ROI, ROImask = initialize_mask(parameters)

    # Reading loop
    while True:
        try:
            status = {
                ord(' '): 'play/pause',
                ord('r'): 'reset',
                9: 'switch mode',  # Tab
                38: 'sel1',  # &
                49: 'sel1',  # 1
                233: 'sel2',  # é
                50: 'sel2',  # 2
                34: 'sel3',  # "
                51: 'sel3',  # 3
                39: 'sel4',  # '
                52: 'sel4',  # 4
                ord('h'): 'switch help',
                -1: status,
                27: 'exit'
            }[cv2.waitKey(1)]

            if (cv2.getWindowProperty('Video Player', 1)
                    == -1) & (i > 1):  # The user closed the window
                status = 'exit'

            if status == 'play':  # mettre en bas ?
                i += 1
                i %= tots

            if tots > 0:  # The two next lines slow down the code a lot !
                cap.set(cv2.CAP_PROP_POS_FRAMES, int(i))
                cv2.setTrackbarPos('S', 'Video Player', int(i))

            _, im = cap.read()

            overlay_ROI = im.copy()  # for transparency
            if np.size(ROI) > 2:
                cv2.drawContours(overlay_ROI, [ROI], 0, (255, 255, 255), 2)
                if not drawingROI:
                    overlay_ROI = cv2.bitwise_and(overlay_ROI,
                                                  overlay_ROI,
                                                  mask=ROImask)
            cv2.addWeighted(overlay_ROI, 0.2, im, 1 - 0.2, 0, im)

            overlay_CL = im.copy()  # for transparency
            for ii, cut_line in enumerate(cut_lines):
                if np.size(cut_line) > 2:
                    cv2.polylines(overlay_CL, [cut_line], 0, lineColors[ii], 3)
            cv2.addWeighted(overlay_CL, 0.8, im, 1 - 0.8, 0, im)

            if mode == 'ROI':
                txt = 'Selection du ROI'
            elif mode == 'CL':
                txt = 'Selection de la ligne de coupe #{}'.format(selectedLine)
            textdim, _ = cv2.getTextSize(txt, cv2.FONT_HERSHEY_DUPLEX, 0.5, 1)
            cv2.rectangle(im, (5 - 1, 20 + 2),
                          (5 + textdim[0] + 1, 20 - textdim[1]),
                          (255, 255, 255), -1)
            cv2.putText(im, txt, (5, 20), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)

            dy = 20
            if showHelp:
                if mode == 'ROI':
                    txt = 'r : remettre a zero le ROI'
                    cv2.putText(im, txt,
                                (5, parameters['Height_Image'] - 5 * dy),
                                cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                    if not drawingROI:
                        txt = 'clic gauche : selectionner le premier point du ROI'
                        cv2.putText(im, txt,
                                    (5, parameters['Height_Image'] - 4 * dy),
                                    cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                    elif drawingROI:
                        txt = 'clic gauche : selectionner le point suivant du ROI'
                        cv2.putText(im, txt,
                                    (5, parameters['Height_Image'] - 4 * dy),
                                    cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                        txt = 'clic droit : selectionner le dernier point du ROI'
                        cv2.putText(im, txt,
                                    (5, parameters['Height_Image'] - 3 * dy),
                                    cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                    txt = 'Tab : passer a la selection de la ligne de coupe'
                    cv2.putText(im, txt,
                                (5, parameters['Height_Image'] - 2 * dy),
                                cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                elif mode == 'CL':
                    txt = '1-4 : selectionner la ligne de coupe #1-4'
                    cv2.putText(im, txt,
                                (5, parameters['Height_Image'] - 6 * dy),
                                cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                    txt = 'r : remettre a zero la ligne de coupe #{}'.format(
                        selectedLine)
                    cv2.putText(im, txt,
                                (5, parameters['Height_Image'] - 5 * dy),
                                cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                    if not drawingCL:
                        txt = 'clic gauche : selectionner le premier point de la ligne de coupe'
                        cv2.putText(im, txt,
                                    (5, parameters['Height_Image'] - 4 * dy),
                                    cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                    elif drawingCL:
                        txt = 'clic gauche : selectionner le point suivant de la ligne de coupe'
                        cv2.putText(im, txt,
                                    (5, parameters['Height_Image'] - 4 * dy),
                                    cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                        txt = 'clic droit : selectionner le dernier point de la ligne de coupe'
                        cv2.putText(im, txt,
                                    (5, parameters['Height_Image'] - 3 * dy),
                                    cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                    txt = 'Tab : passer a la selection du ROI'
                    cv2.putText(im, txt,
                                (5, parameters['Height_Image'] - 2 * dy),
                                cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                txt = 'Esc : quitter'
                cv2.putText(im, txt, (5, parameters['Height_Image'] - dy),
                            cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
                txt = 'h : cacher l\'aide'
                cv2.putText(im, txt, (5, parameters['Height_Image'] - 1),
                            cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)
            else:
                txt = 'h : montrer l\'aide'
                cv2.putText(im, txt, (5, parameters['Height_Image'] - 1),
                            cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1)

            cv2.imshow('Video Player', im)
            if status == 'play':
                continue

            elif status == 'stay':
                i = int(cv2.getTrackbarPos('S', 'Video Player'))

            elif status == 'play/pause':
                status = 'stay' if isRunning else 'play'
                isRunning = not isRunning

            elif status == 'reset':
                if mode == 'ROI':
                    parameters['ROI'] = None
                    ROI, ROImask = initialize_mask(parameters)
                elif mode == 'CL':
                    parameters['Cut_Line' + str(selectedLine)] = None
                    cut_lines = initialize_cut_line(parameters)
                status = 'play' if isRunning else 'stay'

            elif status == 'switch mode':
                if mode == 'ROI':
                    mode = 'CL'
                    selectedLine = 1
                else:
                    mode = 'ROI'
                    selectedLine = 0
                status = 'play' if isRunning else 'stay'

            elif status == 'sel1':
                if not drawingCL:
                    selectedLine = 1
                    mode = 'CL'
                    status = 'play' if isRunning else 'stay'

            elif status == 'sel2':
                if not drawingCL:
                    selectedLine = 2
                    mode = 'CL'
                    status = 'play' if isRunning else 'stay'

            elif status == 'sel3':
                if not drawingCL:
                    selectedLine = 3
                    mode = 'CL'
                    status = 'play' if isRunning else 'stay'

            elif status == 'sel4':
                if not drawingCL:
                    selectedLine = 4
                    mode = 'CL'
                    status = 'play' if isRunning else 'stay'

            elif status == 'switch help':
                showHelp = not showHelp
                status = 'play' if isRunning else 'stay'

            elif status == 'exit':
                answer = messagebox.askquestion(
                    message=
                    'Voulez vous enregistrer les modifications dans le fichier de paramètres ?',
                    type='yesnocancel')
                if answer == 'cancel':
                    status = 'play' if isRunning else 'stay'
                if answer == 'yes':
                    App.parameters = parameters  # Ecraser les anciens paramètres avec les nouveaux
                    df = pandas.read_excel(excelPath, header=None)
                    df.loc[App.comboBoxID.current() + 1, 9] = parameters['ROI']
                    for ii in range(1, 5):
                        df.loc[App.comboBoxID.current() + 1,
                               9 + ii] = parameters['Cut_Line' + str(ii)]
                    try:
                        with pandas.ExcelWriter(excelPath) as writer:
                            df.to_excel(writer,
                                        header=None,
                                        index=False,
                                        sheet_name='All')
                            writer.save
                    except PermissionError:
                        messagebox.showerror(
                            title='Erreur',
                            message=
                            'Impossible d\'enregistrer les modifications, vérifier que le fichier n\'est pas utilisé par une autre application'
                        )
                        status = 'play' if isRunning else 'stay'
                        continue
                    break
                if answer == 'no':
                    break

        except KeyError as e:
            print("Invalid Key \"{:s}: {:d}\" was pressed".format(
                chr(e.args[0]), e.args[0]))

    cv2.destroyAllWindows()
    cap.release()
    return
smile_detector = cv2.CascadeClassifier('data/haarcascade_smile.xml')


def detect(gray, frame):
    faces = face_detector.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), ((x + w), (y + h)), (255, 0, 0), 2)
        roi_gray = gray[y:y + h, x:x + w]
        roi_color = frame[y:y + h, x:x + w]
        smiles = smile_detector.detectMultiScale(roi_gray, 1.8, 20)

        for (sx, sy, sw, sh) in smiles:
            cv2.rectangle(roi_color, (sx, sy), ((sx + sw), (sy + sh)),
                          (0, 0, 255), 2)
    return frame


video_capture = cv2.VideoCapture(0)

while True:
    _, frame = video_capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canvas = detect(gray, frame)
    cv2.imshow('video', canvas)
    if cv2.waitKey(1) & 0xff == ord('q'):
        break
    if cv2.getWindowProperty('video', 1) == -1:
        break

video_capture.release()
cv2.destroyAllWindows()
Exemplo n.º 10
0
        """ when the image is clicked, set the hsv trackbars """
        if event == cv.EVENT_LBUTTONUP:
            b, g, r = get_color(x, y, params)
            hsv.set_trackbars(b, g, r)

    # make a resizable window
    window_name = 'Image'
    cv.namedWindow(window_name, cv.WINDOW_GUI_NORMAL)

    image_file = "/some/path/to/image.png"  # <- path to local image here

    # create the window with the trackbars
    hsv = HSVTrackbars()
    hsv.tolerance = 5

    while bool(cv.getWindowProperty(window_name, cv.WND_PROP_VISIBLE)):
        try:
            img = cv.imread(image_file)
            img = hsv.apply_hsv(img)

            # show the image
            cv.imshow(window_name, img)
            # click on the image to set the hsv values
            cv.setMouseCallback(window_name, on_click, img)

            if cv.waitKey(1) & 0xFF == ord("q"):
                break  # if Q is pressed
        except KeyboardInterrupt:
            break

    # clean up
Exemplo n.º 11
0
def main():
    global STATE, POINTS

    parser = argparse.ArgumentParser(
        description=
        "Interactively select image area and generate a set of icons")

    parser.add_argument(
        "-f",
        "--full",
        action="store_true",
        required=False,
        help=
        "if provided, interactive selection will be skipped. Full image will be used. Image provided has to be a "
        "square image",
    )

    parser.add_argument(
        "filename",
        action="store",
        type=str,
        help="the image file (in freaking any format you want)",
    )

    parser.add_argument(
        "output_directory",
        nargs="?",
        action="store",
        type=str,
        help=
        "the output directory. (For example ./assets/my_icons) If omitted, a directory <img filename>_icons will "
        "be generated under current directory. "
        "It can be a existing directory, otherwise a new directory will be made.",
    )
    argv = parser.parse_args()

    filename = argv.filename

    output_directory = argv.output_directory
    if output_directory is None:

        output_directory = path.splitext(path.basename(filename))[0] + "_icon"
        print("Output directory not provided, using default directory %s" %
              output_directory)

    if isdir(output_directory):
        print(
            "%s is an existing directory. Existing images might be overridden"
            % output_directory)
    else:
        print("new directory %s will be generated." % output_directory)

    assert isfile(filename), "%s is not a file" % filename

    img = imread(filename)

    area_selected = False
    min_x, min_y, max_x, max_y = 0, 0, 0, 0
    if not argv.full:
        imshow("Area Selection", img)
        cv2.setMouseCallback("Area Selection", mouse_callback, img)

        try:
            while cv2.getWindowProperty("Area Selection",
                                        cv2.WND_PROP_VISIBLE) == 1:

                k = cv2.waitKey(1) & 0xFF
                if k == ord("c"):
                    if STATE == NO_POINT:
                        print(
                            "Left click to select, <enter> to confirm, <ESC> to quit, you dumb shit"
                        )

                    elif STATE == ONE_POINT:
                        print("Starting Over...")
                        STATE = NO_POINT
                        cv2.imshow("Area Selection", img)

                    elif STATE == TWO_POINT:
                        print("Re-selecting the second point...")
                        STATE = ONE_POINT
                elif k == 13:  # carriage return

                    min_x = min(POINTS[0], POINTS[1])
                    min_y = min(POINTS[2], POINTS[3])
                    max_x = max(POINTS[0], POINTS[1])
                    max_y = max(POINTS[2], POINTS[3])

                    reselect = False

                    if max_x - min_x >= 5:
                        while True:
                            cv2.imshow("Preview Selection", img[min_y:max_y,
                                                                min_x:max_x])

                            print(
                                "Press <Enter> again to confirm, <c> to reselect, <ESC> to quit"
                            )
                            decision = 255
                            while (cv2.getWindowProperty(
                                    "Preview Selection",
                                    cv2.WND_PROP_VISIBLE) == 1):
                                decision = cv2.waitKey(50) & 0xFF
                                if decision != 255:
                                    break

                            if (cv2.getWindowProperty("Preview Selection",
                                                      cv2.WND_PROP_VISIBLE) !=
                                    1):
                                cv2.destroyAllWindows()
                                sys.exit()
                            if decision == 13:  # carriage return
                                area_selected = True
                                cropped_img = img[min_y:max_y, min_x:max_x]
                                break
                            elif decision == ord("c"):
                                STATE = NO_POINT
                                cv2.imshow("Area Selection", img)
                                print("Re-selecting...")
                                reselect = True
                                break
                            elif decision == 27:
                                print("Selection Canceled")
                                sys.exit()
                            else:
                                print(
                                    "Press <Enter> again to confirm, <c> to reselect, <ESC> to quit. You dumb shit."
                                )
                                continue
                        cv2.destroyWindow("Preview Selection")

                    else:
                        print("Selected Area too small!")
                        print("Re-selecting...")
                        cv2.destroyWindow("Preview Selection")
                        reselect = True
                        STATE = NO_POINT
                        cv2.imshow("Area Selection", img)

                    if not reselect:
                        break
                elif k == 27:
                    print("Selection Canceled")
                    break
                elif k == 255:
                    pass
                else:
                    print(
                        "Left click to select, <enter> to confirm, <ESC> to quit, you dumb shit"
                    )
        except KeyboardInterrupt:
            print("Keyboard Interruption. Selection Canceled")
        finally:
            cv2.destroyAllWindows()
    else:
        assert img.shape[0] == img.shape[1], (
            "File %s is not a square image. It has dimensions %d x %d. Remove -f flag if you want to interactively "
            "crop the image " % (filename, img.shape[0], img.shape[1]))
        area_selected = True
        min_x, min_y = 0, 0
        max_x, max_y = img.shape[0], img.shape[1]

    if area_selected:

        write_icons(img, max_x, max_y, min_x, min_y, output_directory)

        cv2.destroyAllWindows()
Exemplo n.º 12
0
            cv2.putText(frame, name, (left + align_center, bottom - 6), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)

    # resize image
    percent = sets.scale_percent
    width = int(sets.frame_width * percent / 100)
    height = int(sets.frame_height * percent / 100)
    # ratio = sets.ratio
    # width = round(sets.frame_width * ratio)
    # height = round(sets.frame_height * ratio)
    resized = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)

    # Display the resulting image
    if sets.gray_scale:
        grayFrame = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)  # Gray scale
        cv2.imshow(sets.win_name, grayFrame)  # Gray scale
    else:
        cv2.imshow(sets.win_name, resized)  # Color

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    # Close window when close button is pressed
    if cv2.getWindowProperty(sets.win_name, cv2.WND_PROP_VISIBLE) < 1:
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()