Exemplo n.º 1
0
def init(row, col, win_name):
    # win_name = str(x) + str(y)
    if win_name in windowses:
        return

    cv.namedWindow(win_name, cv.WINDOW_NORMAL)
    cv.resizeWindow(win_name, WIN_SIZE[0], WIN_SIZE[1])
    cv.moveWindow(win_name, col * WIN_SIZE[0], row * WIN_SIZE[1])
    windowses.add(win_name)
Exemplo n.º 2
0
def main():
    img = './../img/clip_field.png'
    window_name = 'WindowDAYO'
    img = cv2.imread(img)
    get_circle_point = GetCirclePoint()
    cv2.namedWindow(window_name)
    cv2.setMouseCallback(window_name, get_circle_point.drag_and_drop_square,
                         [window_name, img, get_circle_point])
    cv2.imshow(window_name, img)
    cv2.moveWindow(window_name, 100, 100)  # 左上にウィンドウを出す
    cv2.waitKey()
    print(get_circle_point.named_points)
    cv2.destroyAllWindows()
Exemplo n.º 3
0
 def run_get_circle_point(self):
     img = self.bingo_img
     window_name = self.window_name
     img = cv2.imread(img)
     self.set_get_circle_point(GetCirclePoint(window_name=window_name))
     cv2.namedWindow(window_name)
     cv2.setMouseCallback(window_name,
                          self.get_circle_point.drag_and_drop_square,
                          [window_name, img, self.get_circle_point])
     cv2.imshow(window_name, img)
     cv2.moveWindow(window_name, 100, 100)  # 左上にウィンドウを出す
     cv2.waitKey()
     print(self.get_circle_point.named_points)
Exemplo n.º 4
0
def screen_record():
    while (True):
        sct.get_pixels(frame)
        img = Image.frombytes('RGB', (sct.width, sct.height), sct.image)
        new_screen = find_white(img)
        winname = "Test"
        cv2.namedWindow(winname)
        cv2.moveWindow(winname, 1450, 100)
        cv2.imshow(winname, new_screen)
        n_white_pix = np.sum(new_screen == 255)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break
        return n_white_pix
Exemplo n.º 5
0
def showImageWithBox(dataset):
    for row in dataset:
        if 'LEFT' in dataset[row]:
            if 'CC' in dataset[row]['LEFT']:
                whole_image = loadImage(dataset[row]['LEFT']['CC'][0])
                list_templates = []

                for i in range(1, len(dataset[row]['LEFT']['CC'])):
                    list_templates.append(
                        loadImage(dataset[row]['LEFT']['CC'][i][0])),
                    processImage(dataset[row]['LEFT']['CC'][i][1])

                cv2.imshow("imageLeftCc",
                           resizeImage(searchBox(whole_image, list_templates)))
                cv2.moveWindow("imageLeftCc", 500, 50)
                cv2.waitKey(0)

            if 'MLO' in dataset[row]['LEFT']:
                whole_image = loadImage(dataset[row]['LEFT']['MLO'][0])
                list_templates = []

                for i in range(1, len(dataset[row]['LEFT']['MLO'])):
                    list_templates.append(
                        loadImage(dataset[row]['LEFT']['MLO'][i][0]))
                    processImage(dataset[row]['LEFT']['MLO'][i][1])

                cv2.imshow("imageLeftMlo",
                           resizeImage(searchBox(whole_image, list_templates)))
                cv2.moveWindow("imageLeftMlo", 500, 50)
                cv2.waitKey(0)

        if 'RIGHT' in dataset[row]:
            if 'CC' in dataset[row]['RIGHT']:
                whole_image = loadImage(dataset[row]['RIGHT']['CC'][0])
                list_templates = []

                for i in range(1, len(dataset[row]['RIGHT']['CC'])):
                    list_templates.append(
                        loadImage(dataset[row]['RIGHT']['CC'][i][0]))
                    processImage(dataset[row]['RIGHT']['CC'][i][1])

                cv2.imshow("imageRightCc",
                           resizeImage(searchBox(whole_image, list_templates)))
                cv2.moveWindow("imageRightCc", 500, 50)
                cv2.waitKey(0)

            if 'MLO' in dataset[row]['RIGHT']:
                whole_image = loadImage(dataset[row]['RIGHT']['MLO'][0])
                list_templates = []

                for i in range(1, len(dataset[row]['RIGHT']['MLO'])):
                    list_templates.append(
                        loadImage(dataset[row]['RIGHT']['MLO'][i][0]))
                    processImage(dataset[row]['RIGHT']['MLO'][i][1])

                cv2.imshow("imageRightMlo",
                           resizeImage(searchBox(whole_image, list_templates)))
                cv2.moveWindow("imageRightMlo", 500, 50)
                cv2.waitKey(0)
Exemplo n.º 6
0
def main(decay, velocity):
    source_img = cv2.imread(source)
    target_img = np.zeros_like(source_img)
    row, col = source_img.shape[0], source_img.shape[1]

    center = [col / 2, row / 2]

    x_rel = numpy.matlib.repmat(np.arange(col), row, 1) - center[0]
    y_rel = center[1] - np.transpose(
        numpy.matlib.repmat(np.arange(row), col, 1))

    theta = np.arctan2(y_rel, x_rel)
    r = np.sqrt(pow(x_rel, 2) + pow(y_rel, 2)) + decay * col * np.sin(
        velocity * np.sqrt(pow(x_rel, 2) + pow(y_rel, 2)))

    x_out = r * np.cos(theta) + center[0]
    y_out = center[1] - r * np.sin(theta)

    for i in range(row):
        for j in range(col):
            if x_out[i, j] >= 0 and x_out[i, j] <= col - 1 and y_out[
                    i, j] >= 0 and y_out[i, j] <= row - 1:
                target_img[i, j, :] = bilinear(x_out[i, j], y_out[i, j],
                                               source_img)
            elif i == 0 and j == 0:
                target_img[i, j, :] = [0, 0, 0]
            elif i == 0:
                target_img[i, j, :] = target_img[i, j - 1, :]
            elif j == 0:
                target_img[i, j, :] = target_img[i - 1, j, :]
            else:
                if random.random() < 0.5:
                    target_img[i, j, :] = target_img[i, j - 1, :]
                else:
                    target_img[i, j, :] = target_img[i - 1, j, :]
                # target_img[i, j, :] = target_img[i - 1, j - 1, :]

    target_img = target_img.astype(np.uint8)
    cv2.namedWindow('Water wave', 0)
    cv2.moveWindow('Water wave', 480, 160)
    cv2.imwrite('results/wwtemp.png', target_img)
    cv2.imshow('Water wave', target_img)
    cv2.waitKey()
    cv2.destroyAllWindows()
Exemplo n.º 7
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.º 8
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.")
Exemplo n.º 9
0
    def show(image):
        result = Recognition().recognize(image)

        polygon = []
        for qr in result['qr']:
            pts = np.array(
                list(
                    map(lambda point: [point.x, point.y],
                        qr['location'].points)), np.int32).reshape((-1, 1, 2))
            polygon.append(pts)

        for ring in result['rings']:
            cv2.ellipse(img=image,
                        center=(int(ring.center.x), int(ring.center.y)),
                        axes=(int(ring.maxLength), int(ring.minLength)),
                        angle=ring.angle,
                        color=(0, 255, 255),
                        startAngle=0,
                        endAngle=360)

        cv2.polylines(image, polygon, True, (0, 255, 255))
        cv2.imshow('detected circles', image)
        cv2.moveWindow('detected circles', 20, 20)
Exemplo n.º 10
0
def run():
    read_xml()
    flag, end_path = init_pic()
    if not flag or not end_path:
        print('Init error, not have pictures(filename with .jpg)')
        exit(1)
    clear_end_pic()
    #给随机数一个种子
    random.seed(int(time.time()))
    luck_filenames = []
    #可能会有重复的 多跑十次,还有重复就算了
    for i in range(0, luck_num + 10):
        for j in range(50):
            filename = random_pic_index()
            img = cv2.imread(os.getcwd() + '\\' + pictures + '\\' + filename)
            cv2.namedWindow("process", cv2.WINDOW_NORMAL)
            cv2.moveWindow("process", 600, 200)
            cv2.imshow("process", img)
            cv2.waitKey(50)
        if filename in luck_filenames:
            continue
        luck_filenames.append(filename)
        print('%s  picture: %s' % (datetime.datetime.strftime(
            datetime.datetime.now(), '%Y-%m-%d %H:%M:%S'), filename))
        #拷贝文件
        shutil.copyfile(end_path + '\\' + filename,
                        os.getcwd() + '\\' + end_pic + '\\' + filename)
        img = cv2.imread(os.getcwd() + '\\' + end_pic + '\\' + filename)
        img = cv2.resize(img, (150, 100))
        cv2.namedWindow("result", cv2.WINDOW_NORMAL)
        cv2.moveWindow("result", 500, 150)
        cv2.imshow("result", img)
        cv2.waitKey()
        cv2.destroyAllWindows()
        if len(luck_filenames) >= luck_num:
            break
    input('Please enter and then exit!!!')
Exemplo n.º 11
0
 def display(self) -> None:
     cv2.namedWindow(config.Renderer.WINDOW_NAME)
     cv2.moveWindow(config.Renderer.WINDOW_NAME, 200, 150)
Exemplo n.º 12
0
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]

# start the video stream thread
print("[INFO] starting video stream thread...")
vs = FileVideoStream(args["video"]).start()
fileStream = True

vs = VideoStream(src=0).start()
#vs = FileVideoStream(args["video"]).start()

fileStream = False
time.sleep(1.0)

# opening windows to display images and moving them to right positions
cv2.namedWindow('Frame')
cv2.moveWindow('Frame', 0, 0)

cv2.namedWindow('Left Eye')
cv2.moveWindow('Left Eye', 550, 0)
cv2.namedWindow('Equalized Left Eye')
cv2.moveWindow('Equalized Left Eye', 550, 275)
cv2.namedWindow('Minimum Intensity Left Eye')
cv2.moveWindow('Minimum Intensity Left Eye', 550, 500)

cv2.namedWindow('Right Eye')
cv2.moveWindow('Right Eye', 950, 0)
cv2.namedWindow('Equalized Right Eye')
cv2.moveWindow('Equalized Right Eye', 950, 275)
cv2.namedWindow('Minimum Intensity Right Eye')
cv2.moveWindow('Minimum Intensity Right Eye', 950, 500)
Exemplo n.º 13
0
def showImage(image, text="image", delay=0):
    cv2.namedWindow(text)
    cv2.moveWindow(text, 20, 20)
    cv2.imshow(text, image)
    cv2.waitKey(delay)
Exemplo n.º 14
0
def init_window(name, row=0, col=0):
    cv.namedWindow(name, cv.WINDOW_NORMAL)
    cv.resizeWindow(name, WIN_SIZE[0], WIN_SIZE[1])
    cv.moveWindow(name, col * WIN_SIZE[0], row * WIN_SIZE[1])
    warmup_img = np.zeros(shape=(IMG_SIZE[1], IMG_SIZE[0], 3), dtype=np.uint8)
    show_image(warmup_img, name)
Exemplo n.º 15
0
# Usage:
# m.click(0, 0, 1)  使用 X11 坐标
# k.type_string('Hello, World!')
m = PyMouse()
k = PyKeyboard()

# Screen detection
print('[加载]屏幕参数')
x11_x, x11_y = m.screen_size()
pil_x, pil_y = ImageGrab.grab().size
DPI_times = pil_x / x11_x
EMULATOR_HEADER = 39
EMULATOR_BOTTOM = 42
cv2.namedWindow('output', cv2.WINDOW_NORMAL)
cv2.resizeWindow('output', 500, 500)
cv2.moveWindow('output', int(x11_x) - 500, int(x11_y) - 500)
print('[加载]X11 size:', (x11_x, x11_y))
print('[加载]PIL size:', ImageGrab.grab().size)
print('[加载]DPI times:', DPI_times)

# Helpers - 图像处理
screen_data = None


class ScanIter(object):
    def __init__(self, startp, endp):
        self.start_x, self.start_y = startp
        self.end_x, self.end_y = endp

    def __iter__(self):
        for y in range(self.start_y, self.end_y + 1):
Exemplo n.º 16
0
print('[INFO] starting video stream thread...')
vs = FileVideoStream(args['video']).start()
fileStream = True

vs = VideoStream(src=0).start()

# vs = FileVideoStream(args["video"]).start()

fileStream = False
time.sleep(1.0)

# opening windows to display images and moving them to right positions

cv2.namedWindow('Frame')
cv2.moveWindow('Frame', 0, 0)

cv2.namedWindow('Left Eye')
cv2.moveWindow('Left Eye', 550, 0)
cv2.namedWindow('Equalized Left Eye')
cv2.moveWindow('Equalized Left Eye', 550, 300)

cv2.namedWindow('Right Eye')
cv2.moveWindow('Right Eye', 950, 0)
cv2.namedWindow('Equalized Right Eye')
cv2.moveWindow('Equalized Right Eye', 950, 300)

img_no = 0
phone_call_done = 0
flashlight_done = 0
import numpy as np
from cv2 import cv2

color = cv2.imread("butterfly.jpg", 1)  #w/o one it will still be default 1
print(color.shape)
height, width, channels = color.shape  #Dont messup the order of the height and width
cv2.imshow("Burano Italy", color)
cv2.moveWindow("Burano Italy", 0,
               0)  #Move window to top right corner of screen

######## split channels ##########
b, g, r = cv2.split(color)  #split each channel into new matrix

######## Merge channels ###########

#numpy indexing
# Here we are assigning one width section of rgb_split a value one channel matrix and remaining two channels are kept zero
rgb_split = np.empty([height, width * 3, 3],
                     'uint8')  #Empty uninitialized matrix
rgb_split[:, 0:width,
          0] = b  #blue channel have b, red have zeros and green have zeros
print("Random blue section pixel (b=value/red=0/green=0) = ",
      rgb_split[12, round(width / 2)])
rgb_split[:, width:width * 2, 1] = g
print("Random green section pixel (b=0/red=0/green=value) = ",
      rgb_split[12, round(width * 2 / 2)])

rgb_split[:, width * 2:width * 3, 2] = r
print("Random red section pixel (b=0/red=value/green=0) = ",
      rgb_split[12, round(width * 3 / 2)])
Exemplo n.º 18
0
def showImage(image_path, image):
    cv2.imshow(image_path, image)
    cv2.moveWindow(image_path, 500, 50)
    cv2.waitKey(0)
import numpy as np
from cv2 import cv2
import json
import operator

with open('Output Display/test-result.json', 'r') as f:
    result = json.load(f)

num_faces = len(result)
img = cv2.imread("Output Display/test_img.jpeg", 1)
for i in range(num_faces):
    start_x = result[i]["faceRectangle"]["left"]
    start_y = result[i]["faceRectangle"]["top"]
    end_x = start_x + result[i]["faceRectangle"]["width"]
    end_y = start_y + result[i]["faceRectangle"]["height"]
    cv2.rectangle(img, (start_x, start_y), (end_x, end_y), (0, 0, 255), 2)
    emotions_dict = result[i]["faceAttributes"]["emotion"]
    highest_emotion = max(emotions_dict.items(), key=operator.itemgetter(1))[0]
    cv2.rectangle(img, (start_x, end_y), (end_x, end_y+25),
                  (0, 0, 255), cv2.FILLED)
    cv2.putText(img, highest_emotion, (start_x, end_y+13),
                cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255), 1)
    # cv2.putText(img , highest_emotion,(start_x-5,start_y-5),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255), 2)


cv2.imshow("Image", img)
cv2.moveWindow("Image", 0, 0)

cv2.waitKey(0)
cv2.destroyAllWindows()
Exemplo n.º 20
0
    #Este for es para mostrar los nombres, lo reemplazo con los cuadritos.

    cv2.imshow('Video', frame)

    #Funcion para guardar la cara con un click
    cv2.setMouseCallback('Video', save_face_click)

    cv2.imshow('Video', frame)

    #estas 2 lineas son para sacar la barra de la imagen
    cv2.namedWindow('Video', cv2.WINDOW_NORMAL)
    cv2.setWindowProperty('Video', cv2.WND_PROP_FULLSCREEN,
                          cv2.WINDOW_FULLSCREEN)

    cv2.moveWindow('Video', -35, -20)
    datos_ventana_video = cv2.getWindowImageRect(
        'Video')  #This will return a tuple of (x, y, w, h)

    #Esto es la grilla con fondo negro y datos
    cv2.imshow('grilla', grilla)

    #estas 2 lineas son para sacar la barra de la imagen
    cv2.namedWindow('grilla', cv2.WINDOW_NORMAL)
    cv2.setWindowProperty('grilla', cv2.WND_PROP_FULLSCREEN,
                          cv2.WINDOW_FULLSCREEN)

    #linea para mover la ventana y acomodarlas en la pantalla
    cv2.moveWindow('grilla', datos_ventana_video[0] + datos_ventana_video[2],
                   -20)
Exemplo n.º 21
0
def main():
    """main"""
    # imgは"ndarray"型
    img = cv2.imread('img/sample.jpg')

    if img is None:
        sys.exit("Could not read the image.")

    # unsigned 8 bit format
    img = cv2.cvtColor(img, cv2.CV_8U)
    # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    horizontal_line = "=============================================================="

    print(horizontal_line)
    print("Image Details:")
    print(horizontal_line)
    print("ndarray.ndim", end="\t\t")
    print(img.ndim)
    print("ndarray.shape", end="\t\t")
    print(img.shape)
    print("ndarray.size", end="\t\t")
    print(img.size)
    print("ndarray.dtype", end="\t\t")
    print(img.dtype)
    print("ndarray.itemsize", end="\t")
    print(img.itemsize)
    print("ndarray.data", end="\t\t")
    print(img.data)
    height, width, n_channels = img.shape
    print("HEIGHT (y-axis): " + str(height) + ", WIDTH (x-axis): " +
          str(width) + ", COLOR CHANNELS: " + str(n_channels))
    print(horizontal_line)

    user_input = input(
        "Please press 'y' to see pixel information\n(or press any other key to skip): "
    )
    if user_input == 'y':
        h_digit = len(str(height))
        w_digit = len(str(width))
        for y in range(height):
            for x in range(width):
                print(f"y = {y:>{h_digit}}, x = {x:>{w_digit}}, BGR = ",
                      end="")
                print(img[y, x])
    else:
        print("Skipped.")

    cv2.namedWindow("Original", cv2.WINDOW_AUTOSIZE)
    cv2.moveWindow("Original", 0, 0)
    cv2.imshow("Original", img)

    cv2.namedWindow("Complementary Color", cv2.WINDOW_AUTOSIZE)
    cv2.moveWindow("Complementary Color", 200, 0)
    cv2.imshow("Complementary Color", complementary_color(img))

    # 画像の左下を原点にするためにx軸を中心に反転
    img = cv2.flip(img, 0)

    print(horizontal_line)
    prompt_str = """Select the Affine transformation to perform:
    1 = scale about origin
    2 = translate
    3 = rotate about origin
    4 = rotate about center
    5 = skew in x direction
    6 = skew in y direction
    7 = reflect about x-axis
    8 = reflect about y-axis
    9 = reflect about y=x line
    10 = reflect about origin
    """
    while True:
        user_input = input(prompt_str)
        if user_input == '1':
            affine_matrix = get_affine_tx_matrix_scale(2, 2)
            break
        elif user_input == '2':
            affine_matrix = get_affine_tx_matrix_translate(150, 100)
            break
        elif user_input == '3':
            affine_matrix = get_affine_tx_matrix_rotate_origin(45)
            break
        elif user_input == '4':
            affine_matrix = get_affine_tx_matrix_rotate_center(
                45, width / 2, height / 2)
            break
        elif user_input == '5':
            affine_matrix = get_affine_tx_matrix_skew_x(15)
            break
        elif user_input == '6':
            affine_matrix = get_affine_tx_matrix_skew_y(15)
            break
        elif user_input == '7':
            affine_matrix = get_affine_tx_matrix_reflect_x()
            break
        elif user_input == '8':
            affine_matrix = get_affine_tx_matrix_reflect_y()
            break
        elif user_input == '9':
            affine_matrix = get_affine_tx_matrix_reflect_yx()
            break
        elif user_input == '10':
            affine_matrix = get_affine_tx_matrix_reflect_origin()
            break
        else:
            pass

    print(horizontal_line)
    print('Affine Transformation Matrix:')
    print(affine_matrix)
    print(horizontal_line)
    print('Affine Transformation Matrix for cv2.warpAffine:')

    # 画像の原点を座標軸の原点に移動
    affine_matrix = get_affine_tx_matrix_translate(width,
                                                   height) @ affine_matrix

    # cv2.warpAffineのMには(3, 3) のアフィン変換行列のうち、3行目を除いた (2, 3) の行列を指定
    affine_2x3_matrix = np.delete(affine_matrix, 2, axis=0)
    print(affine_2x3_matrix)
    print(horizontal_line)

    # 背景色(BGR)を指定可能
    dst = cv2.warpAffine(img,
                         M=affine_2x3_matrix,
                         dsize=(width * 3, height * 3),
                         borderValue=(0, 255, 255))

    dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)

    fig = plt.figure(figsize=[6.4, 4.8])
    # 行、列、場所を設定
    ax = fig.add_subplot(1, 1, 1)

    # オリジナル画像の矩形を描画
    rect = plt.Rectangle((0, 0), width, height, fill=0, edgecolor="gray")
    ax.add_patch(rect)

    # 原点をデフォルトの左上ではなく左下にして描画
    # 左下の座標をマイナスに設定
    ax.imshow(dst,
              origin='lower',
              extent=[-width, width * 2, -height, height * 2])
    # plt.imshow(dst, origin='lower')
    ax.set_title("Affine Transformation")
    ax.set_xlabel("x-axis")
    ax.set_ylabel("y-axis")
    # グリッド線を灰色+点線に変更
    ax.grid(color="gray", ls=":")
    # x軸、y軸を破線に設定
    ax.axhline(y=0, color="gray", ls="--")
    ax.axvline(x=0, color="gray", ls="--")

    plt.show(block=False)

    # matplotlibのバックエンドを確認
    backend = matplotlib.get_backend()
    # print(backend)
    if backend == 'TkAgg':
        # ウィンドウの位置を設定
        # geometry (width x height + x-position + y-position)
        mgr = plt.get_current_fig_manager()
        mgr.window.wm_geometry("+0+200")
        # geom = mgr.window.geometry()
        # print(geom)

    user_input = input("Press any key to exit: ")
    # cv2.imwrite("output.png", img)
    cv2.destroyAllWindows()
    plt.clf()
    plt.close('all')
    return 0
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
Exemplo n.º 23
0
    left_camera_matrix, left_distortion, right_camera_matrix, right_distortion,
    size, R, T)
# 计算更正map
left_map1, left_map2 = cv2.initUndistortRectifyMap(left_camera_matrix,
                                                   left_distortion, R1, P1,
                                                   size, cv2.CV_16SC2)
right_map1, right_map2 = cv2.initUndistortRectifyMap(right_camera_matrix,
                                                     right_distortion, R2, P2,
                                                     size, cv2.CV_16SC2)

cv2.namedWindow("left")
cv2.namedWindow("right")
cv2.namedWindow("leftt")
cv2.namedWindow("rightt")
cv2.namedWindow("depth")
cv2.moveWindow("left", 0, 0)
cv2.moveWindow("right", 640, 0)
cv2.moveWindow("leftt", 0, 480)
cv2.moveWindow("rightt", 640, 480)
#cv2.createTrackbar("num", "depth", 0, 10, lambda x: None)
#cv2.createTrackbar("blockSize", "depth", 5, 255, lambda x: None)

videoIn = cv2.VideoCapture(1, cv2.CAP_DSHOW)
videoIn.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
videoIn.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
#cmera2 = cv2.VideoCapture(2)


def draw_min_rect(img, cnt, depth):  # conts = contours
    img = np.copy(img)
    x, y, w, h = cv2.boundingRect(cnt)