def viewResult(sample,idx,prediction,config,save_images_instead=1,size=(384,384)):
    displays = []

    camera_idx = 0
    camera = sample['cameras'][camera_idx]
    subject = sample['subject'][camera_idx]
    action = sample['action'][camera_idx]

    keypoints3d_pred = prediction['keypoints_3d_pred'].cpu()
    keypoints_3d_pred = keypoints3d_pred[0,:, :3].detach().numpy()
    keypoints_3d_gt = sample['keypoints_3d'][:, :3]

    # Project and draw keypoints on images
    for camera_idx in range(len(sample['cameras'])): #camera_indexes_to_show:
        camera = sample['cameras'][camera_idx]

        keypoints_2d_pred = project(camera.projection, keypoints_3d_pred)
        keypoints_2d_gt = project(camera.projection, keypoints_3d_gt)

        # import ipdb; ipdb.set_trace()
        img = sample['images'][camera_idx]

        pred_kind = config.pred_kind if hasattr(config, "pred_kind") else config.kind
        display = vis.draw_2d_pose_cv2(keypoints_2d_pred, img, kind=pred_kind)
        #display = vis.draw_2d_pose_cv2(keypoints_2d_gt, img, kind=config.kind)
        cv2.putText(display, f"Cam {camera_idx:02}", (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0))

        displays.append(display)

    display3 = vis.draw_3d_pose_image(keypoints_3d_pred,kind=pred_kind,radius=450)
    display3 = cv2.cvtColor(display3,cv2.COLOR_RGBA2RGB)
    display3 = cv2.resize(display3, size, interpolation=cv2.INTER_AREA)
    cv2.putText(display3, f"3D prediction", (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0))
    displays.append(display3)

    display3_gt = vis.draw_3d_pose_image(sample['keypoints_3d'][:, :3],kind=pred_kind,radius=450)
    display3_gt = cv2.cvtColor(display3_gt,cv2.COLOR_RGBA2RGB)
    display3_gt = cv2.resize(display3_gt, size, interpolation=cv2.INTER_AREA)
    cv2.putText(display3_gt, f"3D GT", (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0))
    displays.append(display3_gt)

    # Fancy stacked images
    for j, display in enumerate(displays):
        if j == 0:
            combined = display
        else:
            combined = np.concatenate((combined, display), axis=1)

    # Load
    if save_images_instead:
        file = f"./result/result-{subject}-{action}-{camera.name}-{idx}.png"
        cv2.imwrite(file, combined)   
    else:
        cv2.imshow('w', combined)
        cv2.setWindowTitle('w', f"Index {idx}")
        c = cv2.waitKey(0) % 256

        if c == ord('q') or c == 27:
            print('Quitting...')
            cv2.destroyAllWindows()
Пример #2
0
def read_cam(video_capture):
    if video_capture.isOpened():
        windowName = "yolo"
        cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
        cv2.resizeWindow(windowName, 1280, 720)
        cv2.moveWindow(windowName, 0, 0)
        cv2.setWindowTitle(windowName, "Yolo Object Detection")
        while True:
            # Check to see if the user closed the window
            if cv2.getWindowProperty(windowName, 0) < 0:
                break

            ret_val, frame = video_capture.read()
            frame = cv2.resize(frame,(224,224))
            cv2.imshow(windowName, frame)
            frame = np.expand_dims(frame, axis=0)
            frame = preprocess_input(frame)

            preds = model.predict(frame)
            print(preds)
            print('Predicted:', decode_predictions(preds, top=3)[0])

            
            cv2.waitKey(5)

    else:
        print("camera open failed")
Пример #3
0
def take_calibration_images(cam_id=0):
	"""
	Captures calibration images by showing a live feed of the camera and saving the current image when Space is pressed.
	:param cam_settings: Path to the file to load the camera settings from (or None to use Spotter's default settings)
	"""
	v = cv2.VideoCapture(cam_id)

	ensure_folder_exists(CALIB_FOLDER)  # Make sure folder exists to prevent errors on file saving
	for file_name in glob(generate_calibration_filename("{}*".format(CALIB_INPUT_PREFIX))):
		os.remove(file_name)  # Remove any file from a previous calibration so they don't get mixed

	cnt_img = 0
	win_title = "Capturing calibration images - {} captured".format(cnt_img)
	cv2.namedWindow(win_title)
	cv2.moveWindow(win_title, 100,100)
	while True:
		ret, cam_frame = v.read()
		assert ret, "Couldn't grab a frame from cam {}".format(cam_id)
		cv2.imshow(win_title, cv2.resize(cam_frame, dsize=None, fx=0.5, fy=0.5))

		key = cv2.waitKeyEx(1)
		if key == ord(' '):  # Save a new image when Space is pressed
			cnt_img += 1
			file_name = generate_calibration_filename("{}_{}.{}".format(CALIB_INPUT_PREFIX, cnt_img, CALIB_INPUT_FORMAT))
			cv2.setWindowTitle(win_title, "{} - {} captured".format(win_title.split(" - ")[0], cnt_img))
			cv2.imwrite(file_name, cam_frame)
			print("Captured new calibration image: {}".format(file_name))
		elif key >= 0:  # Exit if a key other than Space was pressed
			break

	cv2.destroyAllWindows()
Пример #4
0
def check_with_cnn(image):
    number_img = 255 - image
    number_img = number_img / 255
    found = sum(sum(number_img))
    if 58 < found < 94:
        number_img = cv2.dilate(number_img,
                                np.ones((2, 2), np.uint8),
                                iterations=1)
    elif found < 58:
        number_img = cv2.dilate(number_img,
                                np.ones((3, 3), np.uint8),
                                iterations=1)

    send = number_img.reshape(1, 28, 28, 1)
    chance = model.predict(send)
    chance = chance[0]
    pop = max(chance)
    number = np.argmax(chance)

    if prikazSlanjaCNN:
        cv2.resizeWindow('CNN', 300, 300)
        cv2.imshow('CNN', image)
        cv2.setWindowTitle('CNN', str(number) + " sa " + str(pop))
        cv2.waitKey(1)
        time.sleep(0.5)
    return number, max(chance)
Пример #5
0
def open_display_window(width, height):
    """Open the cv2 window for displaying images with bounding boxeses."""
    cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(WINDOW_NAME, width, height)
    cv2.moveWindow(WINDOW_NAME, 0, 0)
    cv2.setWindowTitle(WINDOW_NAME, 'Camera TFTRT Object Detection Demo '
                                    'for Jetson TX2/TX1')
Пример #6
0
    def run(self):
        cv2.namedWindow("render", cv2.WINDOW_NORMAL)
        cv2.moveWindow("render", self.window_width // 4, self.window_height // 4)
        cv2.resizeWindow('render', self.window_width, self.window_height)

        self.start_time = self.last_time = time.time()
        while True:
            theta = 0.03 * (time.time() - self.start_time)
            view = np.dot(self.view, rotation(theta, 0, 1, 0))
            mvp = np.dot(self.proj, view)

            attributes = {'position': self.vertices}
            if self.colors is not None:
                attributes['color'] = self.colors
            image = rasterize(attributes, self.indices, mvp=mvp, width=self.window_width, height=self.window_height)
            image = image[::-1, :, :]

            cv2.imshow("render", image)
            key = cv2.waitKey(1)
            if key == 27:
                return

            # Display frames per second
            cur_time = time.time()
            dtime = cur_time - self.last_time
            fps = 1.0 / float(dtime + 1e-9)
            self.last_time = cur_time
            cv2.setWindowTitle("render", "Renderer demo, fps = %.2f" % fps)
Пример #7
0
def open_window(width, height):
    cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(WINDOW_NAME, width, height)
    cv2.moveWindow(WINDOW_NAME, 0, 0)
    cv2.setWindowTitle(
        WINDOW_NAME, 'Camera SSD Object Detection Demo '
        'for Jetson TX2/TX1')
    def draw_blob_detection(self,
                            window_name,
                            detect_image,
                            display_image,
                            connectivity=8,
                            minimum_size=0):

        num_labels, labels, stats, centroids = self.blob_detection(
            detect_image, connectivity)

        # Draw circles where blobs where found

        for i, val in enumerate(centroids):
            if stats[i, cv2.CC_STAT_AREA] > minimum_size:
                cv2.circle(display_image,
                           (int(centroids[i][0]), int(centroids[i][1])), 10,
                           (255, 0, 0), 3, 8, 0)

        # Show the result
        cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
        cv2.imshow(window_name, display_image)
        cv2.waitKey(1)

        new_window_name = window_name + ": " + str(num_labels)
        cv2.setWindowTitle(window_name, new_window_name)
Пример #9
0
    def run(self):
        """
        Main processing loop
        """

        try:
            self.distorted_points = points
            self.undistorted_points = targets
            self.quit()
            #self.find_optimal_warp()

        except:
            cv2.namedWindow("window")
            cv.setMouseCallback("window", self.on_mouse, 0)

            while True:  # one frame

                cur_frame = self.cur_frame.copy()
                cur_frame = cv2.resize(cur_frame,
                                       (cur_frame.shape[1] // self.plot_ds,
                                        cur_frame.shape[0] // self.plot_ds))
                cv2.imshow("window", cur_frame)
                title = "Dummy Title"
                cv2.setWindowTitle("window", str(title))

                key = cv2.waitKey(1)
                if key == ord("q"):
                    self.quit()
                    break
                elif key == ord("u"):
                    self.undo()
Пример #10
0
def open_display_window(width, height):
    """Open the cv2 window for displaying images with bounding boxeses."""
    cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(WINDOW_NAME, width, height)
    cv2.moveWindow(WINDOW_NAME, 0, 0)
    cv2.setWindowTitle(WINDOW_NAME, WINDOW_NAME)
    set_full_screen(True)
Пример #11
0
    def run(self):
        cv2.namedWindow("window")
        cv.setMouseCallback("window", self.on_mouse, 0)

        while (self.cont):  # one frame

            if self.new is not None:
                self.plot_axes()

            self.new = None

            cv2.imshow("window", self.cur_image)
            title = "{} toggle class (1), switch frame (8-9), clear all (c), undo(u),   quit (q), switch frame (8-9)".format(
                self.class_names[self.cur_class])
            cv2.setWindowTitle("window", str(title))

            key = cv2.waitKey(1)
            if key == ord('9'):
                self.next()
            # elif key == ord('8'):
            #      self.prev()
            elif key == ord('c'):
                self.clear()
            elif key == ord("q"):
                self.quit()
            elif key == ord("1"):
                self.toggle_class()
            elif key == ord("u"):
                self.undo()
            elif key == ord("d"):
                self.remove()
            elif key == ord("l"):
                self.load()
Пример #12
0
def inone():
    sequence='30'
    path='../data/first/birdview/old/'
    impath = os.path.join(path, sequence)
    list = glob.glob(impath + '/*.png')
    cv2.setWindowTitle("show", "1")
    for i in list:
        label = i.replace('png', 'txt')
        img = cv2.imread(i)
        w, h, c = img.shape
        f = open(label)
        lines = f.readlines()
        f.close()
        for l in lines:
            l = l.split(" ")
            xmid = float(l[1])
            ymid = float(l[2])
            width = float(l[3])
            height = float(l[4])
            xmin = int((xmid - width / 2) * w)
            ymin = int((ymid - height / 2) * h)
            xmax = int((xmid + width / 2) * w)
            ymax = int((ymid + height / 2) * h)
            img = cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (255, 0, 0), 2)
        cv2.imshow("show", img)
        cv2.waitKey()
    cv2.destroyAllWindows()
Пример #13
0
def showpicts(name, wl, begin, end):
    cv.namedWindow('picture', cv.WINDOW_NORMAL)
    for i in range(begin, end + 1):
        pfluor = cv.imread('Test\\' + name + str(i) + '_' + str(wl) + '.tiff', cv.IMREAD_GRAYSCALE)
        p0 = cv.imread('Test\\' + name + str(i) + '_0.tiff', cv.IMREAD_GRAYSCALE)
        p = pfluor - p0
        ma1 = np.max(p)

        if ma1 > 252:
            m, p = cv.threshold(p, 252, 255, cv.THRESH_TOZERO_INV)
            ma1 = np.max(p)

        blur = cv.GaussianBlur(p, (5, 5), 0)
        pshow = (blur * (255 / ma1)).astype(np.uint8)
        cv.imshow('picture', pshow)
        cv.setWindowTitle('picture', 'picture' + str(i))

        # h = cv.calcHist(blur, [0], None, [255], [[0, 255]])

        m, thgauss = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
        print(m)
        cv.namedWindow('threshblur', cv.WINDOW_NORMAL)
        cv.imshow('threshblur', thgauss)
        if cv.waitKey(0) == BTN_ESC:
            cv.destroyAllWindows()
            break
Пример #14
0
    def plot_movements(self):

        denorm = transforms.Normalize(
            mean=[-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.225],
            std=[1 / 0.229, 1 / 0.224, 1 / 0.225])

        avg = denorm(self.running_avg_frame)
        avg = avg.numpy().transpose(1, 2, 0)
        im = avg.copy()

        #plot ignored regions
        # for box in self.cam["ignore"]:
        #     color = (0.1,0.1,0.1) #colors[int(obj.cls)]
        #     c1 =  (int(box[0]),int(box[1]))
        #     c2 =  (int(box[2]),int(box[3]))
        #     im = cv2.rectangle(im,c1,c2,color,1)

        #plot source regions
        for i, box in enumerate(self.sources):
            if self.source_box_classes[i] == 0:
                color = (0.1, 0.9, 0.1)  #colors[int(obj.cls)]
            else:
                color = (0.9, 0.1, 0.1)
            c1 = (int(box[0]), int(box[1]))
            c2 = (int(box[2]), int(box[3]))
            im = cv2.rectangle(im, c1, c2, color, 1)

        for s_idx, source in enumerate(self.sinks):
            for b_idx, box in enumerate(source):
                color = (0.1, 0.1, 0.9)  #colors[int(obj.cls)]
                c1 = (int(box[0]), int(box[1]))
                c2 = (int(box[2]), int(box[3]))
                im = cv2.rectangle(im, c1, c2, color, 1)

        for movement in self.recorded_movements:
            tracks = self.recorded_movements[movement]

            for track in tracks:
                for f in range(len(track) - 1):
                    if np.sum(track[f]) != 0 and np.sum(track[f + 1]) != 0:
                        x0 = int((track[f, 0] + track[f, 2]) / 2.0)
                        y0 = int((track[f, 1] + track[f, 3]) / 2.0)
                        x1 = int((track[f + 1, 0] + track[f + 1, 2]) / 2.0)
                        y1 = int((track[f + 1, 1] + track[f + 1, 3]) / 2.0)
                        color = self.movement_colors[movement - 1]
                        color = (color[0] / 255.0, color[1] / 255.0,
                                 color[2] / 255.0)
                        im = cv2.line(im, (x0, y0), (x1, y1), color, 1)

        #im = cv2.resize(im, (1920,1080))
        cv2.imshow("frame", im)
        cv2.setWindowTitle(
            "frame",
            str("Average frame for {}".format(
                self.sequence_name.split("/")[-1])))
        cv2.imwrite(
            "_output/" + self.sequence_name.split("/")[-1].split(".")[0] +
            "_avg.png", im * 255)
        cv2.waitKey(10)
        cv2.destroyAllWindows()
Пример #15
0
def imshow(name, title, _in):
    img = None

    # Load img if necessary
    if isinstance(_in, str):
        img = imread_rotated(_in)

    elif isinstance(_in, np.ndarray):
        img = _in

    # Load exception if input argument invalid
    if img is None:
        raise TypeError('Expected file path or image')

    # Create window if necessary
    global windows
    if name not in windows:
        windows[name] = cv.namedWindow(name, cv.WINDOW_OPENGL | cv.WINDOW_KEEPRATIO)

    (h, w, _) = img.shape
    if h < w:
        ratio = 1280. / w
    else:
        ratio = 800. / h
    h *= ratio
    w *= ratio

    img = cv.resize(img, None, fx=ratio, fy=ratio)

    cv.imshow(name, img)
    cv.setWindowTitle(name, title)
    cv.resizeWindow(name, int(w), int(h))
Пример #16
0
def main():
    global nameOfImage

    oldNameOfImage = ""
    # font
    font = cv2.FONT_HERSHEY_SIMPLEX
    # org
    org = (50, 50)
    # fontScale
    fontScale = 1
    # Blue color in BGR
    color = (0, 150, 0)
    # Line thickness of 2 px
    thickness = 2

    cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE)
    cv2.setWindowTitle(WINDOW_NAME, 'Click "Q or Esc" to Quit.')

    while True:
        try:
            img = cv2.imread(nameOfImage, cv2.IMREAD_COLOR)
            img = cv2.putText(img, "Today : " + getTime(), org, font,
                              fontScale, color, thickness, cv2.LINE_AA)
            cv2.imshow(WINDOW_NAME, img)
        except:
            pass

        buttonPressed = cv2.waitKey(1)
        if buttonPressed == 27:
            ## Terminate the Program
            break
    cv2.destroyAllWindows()
Пример #17
0
def prepare_window():
    window_name = "Save snapshots"
    cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(window_name, 1280, 720)
    cv2.moveWindow(window_name, 0, 0)
    cv2.setWindowTitle(window_name, "Save snapshots")
    return window_name
def prepare_display_window():
    window = None
    cv2.namedWindow(window, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(window, 1280, 720)
    cv2.moveWindow(window, 0, 0)
    cv2.setWindowTitle(window, "Video capture")
    return window
Пример #19
0
def detect_faces(img, debug=False):
    """检测图片中的人脸并返回第一个有效的人脸区域"""
    # OpenCV的检测效果似乎受图像角度影响很大,因此要尝试旋转图片(顺时针为正)
    rotate_angles = (0, 10, -10, 20, -20, 30, -30, 40, -40, 50, -50, 60, -60)
    for angle in rotate_angles:
        rotated = rotate_bound(img, angle)
        grey = cv.cvtColor(rotated, cv.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(grey, 1.1, 4)
        for area in faces:
            if isValidArea(area):
                face_pos, crop_pos = calc_origin_area(rotated, area, angle,
                                                      img.shape[:2])
                return face_pos, crop_pos
            # 有效区域用绿框标记,无效区域用红框标记
            color = (0, 255, 0) if isValidArea(area) else (0, 0, 255)
            (x, y, w, h) = area
            cv.rectangle(rotated, (x, y), (x + w, y + h), color, 2)
            recog_info = f'({x},{y}), {w}x{h}'
            (h2, w2) = rotated.shape[:2]
            pos = (min(w2 - 170, x), max(y - 10, 12))  # 避免信息显示到绘图区外
            cv.putText(rotated, recog_info, pos, cv.FONT_HERSHEY_SIMPLEX, 0.5,
                       color, 1)
        if debug:
            win_name = "Actress detection"
            cv.imshow(win_name, rotated)
            cv.setWindowTitle(win_name,
                              win_name + f" with ratotion {angle} degrees")
            cv.waitKey(0)
Пример #20
0
 def show(self):
     cv2.imshow(self.contours.filename, self.img)
     cv2.setWindowTitle(self.contours.filename,
                        self.contours.filename + ' ' + self.modoed)
     while True:
         key = cv2.waitKey(1)
         if key != -1:
             print(key)
         if key == 27:
             break
         elif key == 121:  # y
             self.direccion = 'y'
         elif key == 120:  # x
             self.direccion = 'x'
         elif key == 32:  # espacio
             self.direccion = ''
         elif key == 105:  # i
             self.dibimagen = not self.dibimagen
             self.draw_contours()
         elif key == 99:  # c
             self.dibcurvas = not self.dibcurvas
             self.draw_contours()
         elif key == 9:  # tab
             print(self.modoed)
             if self.modoed == 'dib':
                 self.modoed = 'ajuste'
             else:
                 self.modoed = 'dib'
             cv2.setWindowTitle(self.contours.filename,
                                self.contours.filename + ' ' + self.modoed)
     cv2.destroyAllWindows()
Пример #21
0
def vis_detections_cv(im_name, im, dets_all, cls_all, thresh=0.5):
    """Draw detected bounding boxes."""
    assert len(dets_all) == len(cls_all)
    windowName = 'demo_vehicles'
    inds = np.where(dets_all[:, -1] >= thresh)[0]
    for i in inds:
        bbox = dets_all[i, :4]
        score = dets_all[i, -1]
        cls = cls_all[i]
        cv2.rectangle(im, (bbox[0], bbox[1]), (bbox[2], bbox[3]), COLORS[cls],
                      2)
        txt = '{:s} {:.3f}'.format(CLASSES[cls], score)
        cv2.putText(im, txt, (int(bbox[0]) + 1, int(bbox[1]) - 2),
                    cv2.FONT_HERSHEY_PLAIN, 1.0, (32, 32, 32), 4, cv2.LINE_AA)
        cv2.putText(im, txt, (int(bbox[0]), int(bbox[1]) - 2),
                    cv2.FONT_HERSHEY_PLAIN, 1.0, (240, 240, 240), 1,
                    cv2.LINE_AA)
    cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
    height, width, colors = im.shape
    cv2.resizeWindow(windowName, width, height)
    cv2.moveWindow(windowName, 0, 0)
    cv2.setWindowTitle(windowName, im_name)
    cv2.imshow(windowName, im)
    key = cv2.waitKey(0)
    cv2.destroyAllWindows()
Пример #22
0
    def process_img(img, name):
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        shape = gray.shape

        # Find the chess board corners
        ret, corners = cv2.findChessboardCorners(gray, (args.nx, args.ny),
                                                 None, detect_corner_flags)

        # If found, add object points, image points (after refining them)
        if ret:
            objpoints.append(objp)
            imgpoints.append(corners)
            imgs.append(img)
            names.append(name)

            # Draw and display the corners
            img_show = img.copy()
            corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1),
                                        criteria)
            cv2.drawChessboardCorners(img_show, (args.nx, args.ny), corners2,
                                      ret)
            sc = 1024 / np.max(img_show.shape)
            cv2.imshow('detected corners',
                       cv2.resize(img_show, None, fx=sc, fy=sc))
        else:
            print('cant find the corners from %s' % name)
            sc = 1024 / np.max(img.shape)
            cv2.imshow('detected corners', cv2.resize(img, None, fx=sc, fy=sc))
        cv2.setWindowTitle('detected corners', name)
        cv2.waitKey(0 if args.pause else 500)

        return shape
def run(input_path, labels_path, mode=None):
    df_labels: pd.DataFrame = pd.read_csv(labels_path)
    df_labels = df_labels.loc[df_labels['level'] != 0]
    change_list = []
    
    print(f'INFO> Manual annotation of {len(df_labels)} frames starting...')

    cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(WINDOW_NAME, WINDOW_WIDTH, WINDOW_HEIGHT)
    cv2.createTrackbar('progress', WINDOW_NAME, 0, 100, lambda a: None)

    for i, row in tqdm(enumerate(df_labels.itertuples()), smoothing=0, total=len(df_labels)):
        prefix = 'pos' if row.level > 0 else 'neg'
        img = cv2.imread(os.path.join(input_path, prefix, row.image))
        cv2.imshow(WINDOW_NAME, img)
        cv2.setWindowTitle(WINDOW_NAME, f'Name: {os.path.splitext(row.image)[0]} - Grade: {row.level}')

        key_code = cv2.waitKey(0)
        while key_code not in KEYCODES.values():
            key_code = cv2.waitKey(0)

        user_input = get_class_from_key(key_code)
        if user_input != row.level:
            df_labels.loc[row.Index, 'level'] = user_input
            change_list.append((row.image, row.level, user_input))

        cv2.setTrackbarPos('progress', WINDOW_NAME, int(i // (len(df_labels) / 100)))

    cv2.destroyAllWindows()
    df_labels.to_csv(os.path.join(input_path, OUTPUT_NAME))
    print(f'INFO> Manual annotation finished. {len(change_list)} rows affected.')
    print(change_list)
Пример #24
0
    def run(self):  
        self.frame_boxes[self.frame] = self.cur_frame_boxes

        cv2.namedWindow("window")
        cv.setMouseCallback("window", self.on_mouse, 0)
           
        while(self.cont): # one frame
        
           
           
           if self.new is not None:
               self.cur_image = cv2.rectangle(self.cur_image,(self.new[0],self.new[1]),(self.new[2],self.new[3]),self.colors[self.new[4]],2)
               self.new = None
               
           cv2.imshow("window", self.cur_image)
           cv2.setWindowTitle("window",str(self.frame))
           
           key = cv2.waitKey(1)
           if key == ord('2'):
                self.next()
           elif key == ord('1'):
                self.prev()
           elif key == ord('c'):
                self.clear()
           elif key == ord("q"):
                self.quit()
           elif key == ord("0"):
                self.toggle_class()
           elif key == ord("3"):
               self.undo()
Пример #25
0
def imshow(name, title, _in):
    img = None

    # Load img if necessary
    if isinstance(_in, str):
        img = imread_rotated(_in)

    elif isinstance(_in, np.ndarray):
        img = _in

    # Load exception if input argument invalid
    if img is None:
        raise TypeError('Expected file path or image')

    # Create window if necessary
    global windows
    if name not in windows:
        windows[name] = cv.namedWindow(name,
                                       cv.WINDOW_OPENGL | cv.WINDOW_KEEPRATIO)

    (h, w, _) = img.shape
    if h < w:
        ratio = 1280. / w
    else:
        ratio = 800. / h
    h *= ratio
    w *= ratio

    img = cv.resize(img, None, fx=ratio, fy=ratio)

    cv.imshow(name, img)
    cv.setWindowTitle(name, title)
    cv.resizeWindow(name, int(w), int(h))
Пример #26
0
  def loop(self):
    images = self.category.images
    img = None

    load = True
    done = False
    help = True

    i = 0
    key = -1
    while True:
      if help:
        help = False
        if self.helpCallback is not None:
          self.helpCallback(i, self.data)

      if key != -1 and self.keyCallback is not None:
        i2 = i
        i, done, help, load, self.data = self.keyCallback(key, i, self.data)
        if not self.wrap:
          i = max(0, min(len(images)-1, i))
        if i != i2:
          load = True

      if load:
        load = False
        i = i % len(images)
        imgFile = images[i]
        img = cv2.imread(imgFile);
        cv2.setWindowTitle(self.windowName, "{} ({})".format(imgFile.basename, self.title))
        cv2.imshow(self.windowName, img) # show the image

        if self.loadCallback is not None:
          self.overlays, data = self.loadCallback(i, imgFile, self.data)
      if len(self.overlays) > 0:
        imgDrawn = img.copy()
        # draw the overlays
        for overlay in self.overlays:
          box = overlay.rect
          color = overlay.color
          width = overlay.width
          cv2.rectangle(imgDrawn, (box.x,box.y), (box.x+box.width,box.y+box.height), color, width)
        cv2.imshow(self.windowName, imgDrawn) # show the image with the overlay

      # http://stackoverflow.com/questions/35003476/opencv-python-how-to-detect-if-a-window-is-closed/37881722#37881722

      #for j in range(4):
      #  print("{}	{}".format(j, cv2.getWindowProperty(self.windowName, j)))
      #print()
      if cv2.getWindowProperty(self.windowName, 1) != 0:
        done = True

      if done:
        # http://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
        cv2.destroyWindow(self.windowName)
        for i in range(4):
          cv2.waitKey(1)
        return self.data
      key = cv2.waitKey(10) #wait 10 ms for a key press
Пример #27
0
def open_window(window_name, title, width=None, height=None):
    """Open the display window."""
    print(1)
    cv2.namedWindow('image', 0)
    print(2)
    cv2.setWindowTitle(window_name, title)
    if width and height:
        cv2.resizeWindow(window_name, width, height)
Пример #28
0
def show_image(image, fps):
    global is_streaming
    cv2.imshow('unique_window_identifier', image)
    cv2.setWindowTitle("unique_window_identifier", f"fps= {fps}")
    # Press Q to Quit
    if cv2.waitKey(1) == ord('q'):
        camera.image_received_cb.remove_callback(show_image)
        is_streaming = False
Пример #29
0
def show_image(title, img):
    cv2.namedWindow('window', cv2.WINDOW_NORMAL)
    cv2.setWindowTitle('window', title)
    cv2.imshow('window', img)
    value = cv2.waitKey(0)
    if value == 27:
        os._exit(1)
    return value
Пример #30
0
def show_image(__self__):
    """Creates the window and displays an image file"""
    name = 'ImageViewer'
    frame = cv2.imread(__self__, 1)
    cv2.namedWindow(name, cv2.WINDOW_GUI_NORMAL)
    cv2.setWindowProperty(name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_KEEPRATIO)
    cv2.setWindowTitle(name, __self__)
    cv2.imshow(name, frame)
Пример #31
0
    def main(args):
        frame_interval = 3  # Number of frames after which to run face detection
        fps_display_interval = 5  # seconds
        frame_rate = 0
        frame_count = 0
        count = 0
        save_path = str('/work/MachineLearning/my_dataset/train_aligned/' +
                        args.name)

        if not os.path.exists(save_path):
            os.mkdir(save_path)

        print("Saving images into " + save_path)
        video_capture = cv2.VideoCapture(0)
        face_detection = face.Detection()
        #   face_recognition = face.Recognition()
        start_time = time.time()

        while True:
            # Capture frame-by-frame
            ret, frame = video_capture.read()

            if (frame_count % frame_interval) == 0:
                faces = face_detection.find_faces(frame)

                # Check our current fps
                end_time = time.time()
                if (end_time - start_time) > fps_display_interval:
                    frame_rate = int(frame_count / (end_time - start_time))
                    start_time = time.time()
                    frame_count = 0

    #        add_overlays(frame, faces, frame_rate)

            frame_count += 1
            if len(faces) == 1:
                frame = faces[0].image
                cv2.imshow('Enrolling', frame)
                cv2.setWindowTitle('Enrolling',
                                   str(args.name) + " " + str(count + 1))
                #cv2.putText(faces[0].image, 'Image: ' + str(frame_count+1), (0, 0), cv2.FONT_HERSHEY_SIMPLEX, 1,
                #            (255, 0, 0), thickness=2, lineType=2)
                rgb_frame = frame[:, :, ::-1]
                img = Image.fromarray(rgb_frame, "RGB")
                if img is not None:
                    img.save(
                        os.path.join(save_path + "/" + str(count) + ".jpg"))
                count += 1

                #if frame_count > 100:
                #   break

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        # When everything is done, release the capture
        video_capture.release()
        cv2.destroyAllWindows()
Пример #32
0
def imshow(name, img):
    # Make it 800px wide on major axis
    (h, w, _) = img.shape
    if h < w:
        ratio = 800.0 / w
    else:
        ratio = 500.0 / h
    h *= ratio
    w *= ratio

    cv.imshow("main", img)
    cv.setWindowTitle("main", name)
    cv.resizeWindow("main", int(w), int(h))


# while (True):
while cap.isOpened():  # 检查是否成功初始化,否则就 使用函数 cap.open()
    # Capture frame-by-frame
    ret, frame = cap.read()  # ret 返回一个布尔值 True/False
    # print('frame shape:',frame.shape)#(720, 1280, 3)

    frame = cv2.flip(frame, flipCode=1)  # 左右翻转,使用笔记本电脑摄像头才有用。
    # flipCode:翻转方向:1:水平翻转;0:垂直翻转;-1:水平垂直翻转

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame', gray)
    cv2.setWindowTitle('frame', 'COLOR_BGR2GRAY')

    # Property=cv2.getWindowProperty('frame',0)#无用

    # if cv2.waitKey(1) & 0xFF == ord('q'):#不行
    #     break
    key = cv2.waitKey(delay=10)
    if key == ord("q"):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
    if not state.scale or out.shape[:2] == (h, w):
        pointcloud(out, verts, texcoords, color_source)
    else:
        tmp = np.zeros((h, w, 3), dtype=np.uint8)
        pointcloud(tmp, verts, texcoords, color_source)
        tmp = cv2.resize(
            tmp, out.shape[:2][::-1], interpolation=cv2.INTER_NEAREST)
        np.putmask(out, tmp > 0, tmp)

    if any(state.mouse_btns):
        axes(out, view(state.pivot), state.rotation, thickness=4)

    dt = time.time() - now

    cv2.setWindowTitle(
        state.WIN_NAME, "RealSense (%dx%d) %dFPS (%.2fms) %s" %
        (w, h, 1.0/dt, dt*1000, "PAUSED" if state.paused else ""))

    cv2.imshow(state.WIN_NAME, out)
    key = cv2.waitKey(1)

    if key == ord("r"):
        state.reset()

    if key == ord("p"):
        state.paused ^= True

    if key == ord("d"):
        state.decimate = (state.decimate + 1) % 3
        decimate.set_option(rs.option.filter_magnitude, 2 ** state.decimate)
Пример #35
0
Файл: ui.py Проект: aevri/mel
 def set_title(self, title):
     cv2.setWindowTitle(self.name, title)
Пример #36
0
import cv2
import numpy as np

cap0 = cv2.VideoCapture(0)
cap1 = cv2.VideoCapture(1)
ret = cap0.set(3, 320)
ret = cap0.set(4, 240)
ret = cap1.set(3, 320)
ret = cap1.set(4, 240)

while cap0.isOpened() and cap1.isOpened():
    ret0, frame0 = cap0.read()
    ret1, frame1 = cap1.read()

    if ret0:
        cv2.imshow('frame0', frame0)
        cv2.setWindowTitle('frame0','On Top')
    if ret1:
        cv2.imshow('frame1', frame1)
        # cv2.moveWindow('frame1', x=frame0.shape[1], y=0)
        cv2.moveWindow('frame1', x=320, y=40)

    key = cv2.waitKey(delay=2)
    if key == ord("q"):
        break

# When everything done, release the capture
cap0.release()
cap1.release()
cv2.destroyAllWindows()