예제 #1
0
def window(name):
	# Create a frame for this window and fill it with a nice color
	frame = np.zeros((200, 500, 3), np.uint8)
	frame[:] = (49, 52, 49)

	# Inform cvui that the components to be rendered from now one belong to
	# a window in particular.
	#
	# If you don't inform that, cvui will assume the components belong to
	# the default window (informed in cvui.init()). In that case, the
	# interactions with all other windows being used will not work.
	cvui.context(name)

	# Show info regarding the window
	cvui.printf(frame, 110, 50, '%s - click the button', name)

	# Buttons return true if they are clicked
	if cvui.button(frame, 110, 90, 'Button'):
		cvui.printf(frame, 200, 95, 'Button clicked!')
		print('Button clicked on: ', name)

	# Tell cvui to update its internal structures regarding a particular window.
	#
	# If cvui is being used in multiple windows, you need to enclose all component
	# calls between the pair cvui.context(NAME)/cvui.update(NAME), where NAME is
	# the name of the window being worked on.
	cvui.update(name)

	# Show the content of this window on the screen
	cvui.imshow(name, frame)
예제 #2
0
파일: hello-world.py 프로젝트: Dovyski/cvui
def main():
	frame = np.zeros((200, 500, 3), np.uint8)
	count = 0;

	# Init cvui and tell it to create a OpenCV window, i.e. cv::namedWindow(WINDOW_NAME).
	cvui.init(WINDOW_NAME)

	while (True):
		# Fill the frame with a nice color
		frame[:] = (49, 52, 49)

		# Buttons will return true if they were clicked, which makes
		# handling clicks a breeze.
		if (cvui.button(frame, 110, 80, "Hello, world!")):
			# The button was clicked, so let's increment our counter.
			count += 1

		# Sometimes you want to show text that is not that simple, e.g. strings + numbers.
		# You can use cvui::printf for that. It accepts a variable number of parameter, pretty
		# much like printf does.
		# Let's show how many times the button has been clicked.
		cvui.printf(frame, 250, 90, 0.4, 0xff0000, "Button click count: %d", count);

		# Update cvui stuff and show everything on the screen
		cvui.imshow(WINDOW_NAME, frame);

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
def main():
    frame = np.zeros((200, 500, 3), np.uint8)
    count = 0

    # Init cvui and tell it to create a OpenCV window, i.e. cv::namedWindow(WINDOW_NAME).
    cvui.init(WINDOW_NAME)

    while (True):
        # Fill the frame with a nice color
        frame[:] = (49, 52, 49)

        # Buttons will return true if they were clicked, which makes
        # handling clicks a breeze.
        if (cvui.button(frame, 110, 80, "Hello, world!")):
            # The button was clicked, so let's increment our counter.
            count += 1

        # Sometimes you want to show text that is not that simple, e.g. strings + numbers.
        # You can use cvui::printf for that. It accepts a variable number of parameter, pretty
        # much like printf does.
        # Let's show how many times the button has been clicked.
        cvui.printf(frame, 250, 90, 0.4, 0xff0000, "Button click count: %d",
                    count)

        # Update cvui stuff and show everything on the screen
        cvui.imshow(WINDOW_NAME, frame)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
예제 #4
0
def wellOrganisation(self, controller, circular, rectangular, roi, other,
                     multipleROIs):
    if multipleROIs:
        controller.show_frame("NbRegionsOfInterest")
    else:
        if rectangular:
            self.shape = 'rectangular'
            self.configFile["wellsAreRectangles"] = 1
            controller.show_frame("CircularOrRectangularWells")
        else:
            if circular and self.organism != 'drosoorrodent':  # should remove the self.organism != 'drosoorrodent' at some point
                self.shape = 'circular'
                controller.show_frame("CircularOrRectangularWells")
            else:
                self.shape = 'other'
                if roi:
                    cap = cv2.VideoCapture(self.videoToCreateConfigFileFor)
                    cap.set(1, 10)
                    ret, frame = cap.read()
                    frame2 = frame.copy()
                    [
                        frame2, getRealValueCoefX, getRealValueCoefY,
                        horizontal, vertical
                    ] = resizeImageTooLarge(frame2, True, 0.85)

                    WINDOW_NAME = "Click on the top left of the region of interest"
                    cvui.init(WINDOW_NAME)
                    cv2.moveWindow(WINDOW_NAME, 0, 0)
                    cvui.imshow(WINDOW_NAME, frame2)
                    while not (cvui.mouse(cvui.CLICK)):
                        cursor = cvui.mouse()
                        if cv2.waitKey(20) == 27:
                            break
                    self.configFile["oneWellManuallyChosenTopLeft"] = [
                        int(getRealValueCoefX * cursor.x),
                        int(getRealValueCoefY * cursor.y)
                    ]
                    cv2.destroyAllWindows()

                    WINDOW_NAME = "Click on the bottom right of the region of interest"
                    cvui.init(WINDOW_NAME)
                    cv2.moveWindow(WINDOW_NAME, 0, 0)
                    cvui.imshow(WINDOW_NAME, frame2)
                    while not (cvui.mouse(cvui.CLICK)):
                        cursor = cvui.mouse()
                        if cv2.waitKey(20) == 27:
                            break
                    self.configFile["oneWellManuallyChosenBottomRight"] = [
                        int(getRealValueCoefX * cursor.x),
                        int(getRealValueCoefY * cursor.y)
                    ]
                    cv2.destroyAllWindows()

                    self.configFile["nbWells"] = 1
                    chooseBeginningAndEndOfVideo(self, controller)
                else:
                    self.configFile["noWellDetection"] = 1
                    self.configFile["nbWells"] = 1
                    chooseBeginningAndEndOfVideo(self, controller)
예제 #5
0
def main(save_dir, laser_off):
    make_save_dir(save_dir)
    rs_mng = RealSenseManager()  # default image size = (1280, 720)
    if laser_off:
        rs_mng.laser_turn_off()
    else:
        rs_mng.laser_turn_on()

    image_width, image_height = rs_mng.image_size

    res_image_width = int(image_width * 2 / 3)
    res_image_height = int(image_height * 2 / 3)
    window_image_width = int(image_width * 4 / 3)
    window_image_height = int(image_height)

    cvui.init("capture")
    frame = np.zeros((window_image_height, window_image_width, 3), np.uint8)
    captured_frame_count = count_images(save_dir)

    while True:
        key = cv2.waitKey(10)
        frame[:] = (49, 52, 49)

        status = rs_mng.update()
        if status:
            # Get Images
            ir_image_left = rs_mng.ir_frame_left
            ir_image_right = rs_mng.ir_frame_right
            color_image = rs_mng.color_frame
            depth_image = rs_mng.depth_frame
            depth_image_aligned2color = rs_mng.depth_frame_aligned2color

            # Visualize Images
            frame = draw_frames(frame, color_image, depth_image,
                                res_image_width, res_image_height)

            if cvui.button(frame, 50, res_image_height + 50, 130, 50,
                           "Save Result Image") or key & 0xFF == ord("s"):
                save_images(color_image, depth_image,
                            depth_image_aligned2color, ir_image_left,
                            ir_image_right, save_dir)
                captured_frame_count += 1

            if cvui.button(frame, 200, res_image_height + 50, 130, 50,
                           "Clear"):
                clean_save_dir(save_dir)
                captured_frame_count = 0

            cvui.printf(frame, 50, res_image_height + 150, 0.8, 0x00FF00,
                        "Number of Captured Images : %d", captured_frame_count)
            if key & 0xFF == ord("q"):
                break

            cvui.update()
            cvui.imshow("capture", frame)

    cv2.destroyAllWindows()
    del rs_mng
예제 #6
0
def main(camera_toml_path, enable_distortion_correction, scale_val = 0.65):
    camera_config = get_config(camera_toml_path)
    camera = Camera(camera_config)
    print(camera)

    scaling = partial(scaling_int, scale=scale_val)
    if camera_config.roi_size != 4:
        sys.exit('This script is only supported on "camera_config.roi_size == 4" ')
    if camera_config.auto_exposure != "roi":
        sys.exit('This script is only supported on "camera_config.auto_exposure == roi" ')

    image_width = camera.image_width
    image_height = camera.image_height

    roi = cvui.Rect(0, 0, 0, 0)
    WINDOW_NAME = "Capture"
    cvui.init(WINDOW_NAME)
    click_pos_x = image_width // 2
    click_pos_y = image_height // 2

    while True:
        key = cv2.waitKey(10)
        frame = np.zeros((scaling(image_height), scaling(image_width), 3), np.uint8)
        frame[:] = (49, 52, 49)

        status = camera.update()
        if status:
            # WARNING:If distortion correction is enabled, the rectangle on windows doesn't indicate actual RoI area for auto exposure.
            see3cam_rgb_image = camera.remap_image if enable_distortion_correction else camera.image
            scaled_width = scaling(image_width)
            scaled_height = scaling(image_height)
            see3cam_rgb_image_resized = cv2.resize(see3cam_rgb_image, (scaled_width, scaled_height))
            frame[:scaled_height, :scaled_width, :] = see3cam_rgb_image_resized

            window_w = image_width // 2
            window_h = image_height // 2
            if cvui.mouse(cvui.DOWN):
                click_pos_x = int(cvui.mouse().x / scale_val)
                click_pos_y = int(cvui.mouse().y / scale_val)

            camera.set_roi_properties(click_pos_x, click_pos_y, win_size=4)
            roi = cvui.Rect(scaling(click_pos_x - image_width // 4), scaling(click_pos_y - image_height // 4), scaling(window_w), scaling(window_h))

            # Ensure ROI is within bounds
            roi.x = 0 if roi.x < 0 else roi.x
            roi.y = 0 if roi.y < 0 else roi.y

            roi.width = roi.width + scaled_width - (roi.x + roi.width) if roi.x + roi.width > scaled_width else roi.width
            roi.height = roi.height + scaled_height - (roi.y + roi.height) if roi.y + roi.height > scaled_height else roi.height

            cvui.rect(frame, roi.x, roi.y, roi.width, roi.height, 0xFF0000)

        if key == 27 or key == ord("q"):
            break

        cvui.update()
        cvui.imshow(WINDOW_NAME, frame)
    cv2.destroyAllWindows()
예제 #7
0
 def windows_show(self):
     cvui.update()
     cvui.context(self.mainwindow_name)
     cvui.imshow(self.mainwindow_name, self.mainframe)
     cv2.displayStatusBar(
         self.mainwindow_name,
         "{:3.2f}pmm X:{:03d} Y:{:03d} Focus:{:05d} Contours:{:02d} Xmm:{:7.2f}  Ymm{:7.2f} Color:{}"
         .format(self.cal_line_distance_total, self.mouse_x, self.mouse_y,
                 int(self.focus_value), self.contours_found_quan,
                 self.actual_mm_x, self.actual_mm_y,
                 str(self.mouse_color)), 0)
def adjustHyperparameters(l, hyperparameters, hyperparametersListNames, frameToShow, WINDOW_NAME, organizationTab):
  
  root = tk.Tk()
  horizontal = root.winfo_screenwidth()
  vertical   = root.winfo_screenheight()
  if len(frameToShow[0]) > horizontal or len(frameToShow) > vertical:
    frameToShow = cv2.resize(frameToShow, (int(horizontal*0.8), int(vertical*0.8)))
  root.destroy()
  
  WINDOW_NAME_CTRL = "Adjust Parameters."
  frameNum            = [l]
  hyperparametersList = [[hyperparameters[name]] for name in hyperparametersListNames]
  frameCtrlLengthY = math.ceil((len(hyperparametersListNames) + 2)/2) * 70 + 20
  
  buttonclicked = False
  while frameNum[0] == l and hyperparametersList == [[hyperparameters[name]] for name in hyperparametersListNames] and not(buttonclicked):
    
    frameCtrl = np.full((frameCtrlLengthY, 1100), 100).astype('uint8')
    printStuffOnCtrlImg(frameCtrl, frameNum, 1, 35, 350, hyperparameters["firstFrame"], hyperparameters["lastFrame"], "Frame number", "You can also go through the video with the keys a or 4 (backward); d or 6 (forward); f or g (fast backward); h or j (fast forward)")
    for idx, hyperParamCurVal in enumerate(hyperparametersList):
      [minn, maxx] = printStuffOnCtrlImg(frameCtrl, hyperParamCurVal, organizationTab[idx][0], organizationTab[idx][1], organizationTab[idx][2], organizationTab[idx][3], organizationTab[idx][4], hyperparametersListNames[idx], organizationTab[idx][5])
      organizationTab[idx][3] = minn
      organizationTab[idx][4] = maxx
    
    buttonclicked = cvui.button(frameCtrl, organizationTab[len(organizationTab)-1][0], organizationTab[len(organizationTab)-1][1], "Ok, done!")
    # cvui.text(frameCtrl, 100, 245, 'Warning: for some of the "overwrite" parameters, you will need to change the initial value for the "overwrite" to take effect.')
    cvui.imshow(WINDOW_NAME, frameToShow)
    cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)
    r = cv2.waitKey(20)
    if (r == 54) or (r == 100) or (r == 0):
      frameNum[0] = frameNum[0] + 1
    elif (r == 52) or (r == 97) or (r == 113):
      frameNum[0] = frameNum[0] - 1
  l = int(frameNum[0])
  if l >= hyperparameters["lastFrame"]:
    l = hyperparameters["lastFrame"] - 1
  if l <= hyperparameters["firstFrame"]:
    l = hyperparameters["firstFrame"]
  
  for idx, hyperParamCurVal in enumerate(hyperparametersList):
    hyperparameters[hyperparametersListNames[idx]] = hyperParamCurVal[0]
  if buttonclicked:
    newhyperparameters = {}
    for idx, hyperparameterName in enumerate(hyperparametersListNames):
      newhyperparameters[hyperparameterName] = hyperparameters[hyperparameterName]
    pickle.dump(newhyperparameters, open('newhyperparameters', 'wb'))
    cv2.destroyAllWindows()
    raise ValueError

  return [l, hyperparameters, organizationTab]
예제 #9
0
def main(toml_path, directory_for_save, config_name, rgb_rate,
         scale_for_visualization):
    rgb_manager = RGBCaptureManager(toml_path)
    inference = create_inference(config_name)
    width, height = rgb_manager.size
    scaling = partial(scaling_int, scale=scale_for_visualization)

    width_resized = scaling(width)
    height_resized = scaling(height)
    frame = np.zeros((height_resized + 300, width_resized * 2, 3), np.uint8)

    WINDOW_NAME = "Capture"
    cvui.init(WINDOW_NAME)
    while True:
        frame[:] = (49, 52, 49)
        key = cv2.waitKey(10)
        status = rgb_manager.update()
        if not status:
            continue

        rgb_image_raw = rgb_manager.read()
        rgb_image_masked = get_masked_image_with_segmentation(
            rgb_image_raw, rgb_manager, inference, rgb_rate)

        number_of_saved_frame = get_number_of_saved_image(directory_for_save)
        cvui.printf(frame, 50, height_resized + 50, 0.8, 0x00FF00,
                    "Number of Captured Images : %d", number_of_saved_frame)
        if cvui.button(frame, 50, height_resized + 110, 200, 100,
                       "capture image") or key & 0xFF == ord("s"):
            save_image(rgb_image_raw, directory_for_save)

        if cvui.button(frame, 300, height_resized + 110, 200, 100, "erase"):
            clean_save_dir(directory_for_save)

        rgb_image_resized = cv2.resize(rgb_image_raw,
                                       (width_resized, height_resized))
        masked_image_resized = cv2.resize(rgb_image_masked,
                                          (width_resized, height_resized))
        frame[0:height_resized, 0:width_resized, :] = rgb_image_resized
        frame[0:height_resized,
              width_resized:(width_resized * 2), :] = masked_image_resized

        if key == 27 or key == ord("q"):
            break

        cvui.update()
        cvui.imshow(WINDOW_NAME, frame)

    cv2.destroyAllWindows()
예제 #10
0
def findTailTipByUserInput(frame, frameNumber, videoPath, hyperparameters):
    # global ix
    # ix = -1
    # img = np.zeros((512,512,3), np.uint8)
    # cv2.namedWindow('Click on tail tip')
    # cv2.setMouseCallback('Click on tail tip',getXYCoordinates)
    # print("ix:", ix)
    # while(ix == -1):
    # cv2.imshow('Click on tail tip',frame)
    # k = cv2.waitKey(20) & 0xFF
    # if k == 27:
    # break
    # elif k == ord('a'):
    # print("yeah:",ix,iy)
    # cv2.destroyAllWindows()
    # return [ix,iy]

    WINDOW_NAME = "Click on tail tip"
    cvui.init(WINDOW_NAME)
    cv2.moveWindow(WINDOW_NAME, 0, 0)

    font = cv2.FONT_HERSHEY_SIMPLEX
    frame = cv2.rectangle(frame, (0, 0), (250, 29), (255, 255, 255), -1)
    cv2.putText(frame, 'Click any key if the tail is', (1, 10), font, 0.5,
                (0, 150, 0), 1, cv2.LINE_AA)
    cv2.putText(frame, 'not straight on this image', (1, 22), font, 0.5,
                (0, 150, 0), 1, cv2.LINE_AA)

    cvui.imshow(WINDOW_NAME, frame)
    plus = 1
    while not (cvui.mouse(WINDOW_NAME, cvui.CLICK)):
        cursor = cvui.mouse(WINDOW_NAME)
        if cv2.waitKey(20) != -1:
            [frame, thresh1] = headEmbededFrame(videoPath, frameNumber + plus,
                                                hyperparameters)
            frame = cv2.rectangle(frame, (0, 0), (250, 29), (255, 255, 255),
                                  -1)
            cv2.putText(frame, 'Click any key if the tail is', (1, 10), font,
                        0.5, (0, 150, 0), 1, cv2.LINE_AA)
            cv2.putText(frame, 'not straight on this image', (1, 22), font,
                        0.5, (0, 150, 0), 1, cv2.LINE_AA)
            cvui.imshow(WINDOW_NAME, frame)
            plus = plus + 1
    # cv2.destroyAllWindows()
    cv2.destroyWindow(WINDOW_NAME)
    return [cursor.x, cursor.y]
def main():
    frame = np.zeros((600, 800, 3), np.uint8)
    value = [50]

    settings = EnhancedWindow(20, 80, 200, 120, 'Settings')
    info = EnhancedWindow(250, 80, 330, 60, 'Info')

    # Init cvui and tell it to create a OpenCV window, i.e. cv2.namedWindow(WINDOW_NAME).
    cvui.init(WINDOW_NAME)

    while (True):
        # Fill the frame with a nice color
        frame[:] = (49, 52, 49)

        # Place some instructions on the screen regarding the
        # settings window
        cvui.text(
            frame, 20, 20,
            'The Settings and the Info windows below are movable and minimizable.'
        )
        cvui.text(frame, 20, 40,
                  'Click and drag any window\'s title bar to move it around.')

        # Render a movable and minimizable settings window using
        # the EnhancedWindow class.
        settings.begin(frame)
        if settings.isMinimized() == False:
            cvui.text('Adjust something')
            cvui.space(10)  # add 10px of space between UI components
            cvui.trackbar(settings.width() - 20, value, 5, 150)
        settings.end()

        # Render a movable and minimizable settings window using
        # the EnhancedWindow class.
        info.begin(frame)
        if info.isMinimized() == False:
            cvui.text('Moving and minimizable windows are awesome!')
        info.end()

        # Update all cvui internal stuff, e.g. handle mouse clicks, and show
        # everything on the screen.
        cvui.imshow(WINDOW_NAME, frame)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
예제 #12
0
    def run(self):
        WINDOW_NAME = "viewer"
        self._start()
        cvui.init(WINDOW_NAME)

        frame = np.zeros((960, 1280, 3), np.uint8)
        while True:
            frame[:] = (49, 52, 49)
            cvui.text(frame, 10, 10, 'See3CAM', 0.5)
            k = cv2.waitKey(10)
            if k == 27 or k == ord('q'):
                self._stopped = True
                break
            elif k == ord('s'):
                self._save_image()
            self._cvui_gui(frame)
            cvui.imshow(WINDOW_NAME, frame)
        cv2.destroyAllWindows()
예제 #13
0
def launchStuff():
    if globalVariables["mac"] != 1 and globalVariables["lin"] != 1:
        WINDOW_NAME = "Tracking in Progress"
        cvui.init(WINDOW_NAME)
        cv2.moveWindow(WINDOW_NAME, 0, 0)
        f = open("trace.txt", "r")
        if f.mode == 'r':
            contents = f.read()
        f.close()
        while not ("ZebraZoom Analysis finished for" in contents):
            f = open("trace.txt", "r")
            if f.mode == 'r':
                contents = f.read()
            f.close()
            frameCtrl = np.full((400, 500), 100).astype('uint8')
            contentList = contents.split("\n")
            for idx, txt in enumerate(contentList):
                cvui.text(frameCtrl, 4, 15 + idx * 20, txt)
            cvui.imshow(WINDOW_NAME, frameCtrl)
            cv2.waitKey(20)
        cv2.destroyAllWindows()
예제 #14
0
 def update_cvui(self):
     if self.cvui_frame is None:
         return
     self.cvui_frame[:] = (49, 52, 49)
     if True:
         cvui.text(self.cvui_frame, 20, 30, 'DBSCAN')
         cvui.text(self.cvui_frame, 40, 60, 'eps')
         cvui.counter(self.cvui_frame, 110, 55, self.cvui_dbscan_eps, 0.001,
                      '%.3f')
         cvui.text(self.cvui_frame, 40, 90, 'minpoints')
         cvui.counter(self.cvui_frame, 110, 85, self.cvui_dbscan_minpoints,
                      1, '%d')
     cvui.imshow(CVUI_WINDOW_NAME, self.cvui_frame)
     cv_key = cv2.waitKey(1)
     if cv_key == 27:
         self.call_exit()
     elif cv_key == 110:
         self.call_next()
     elif cv_key == 98:
         self.call_prev()
     elif cv_key == 114:
         self.call_refit()
     elif cv_key == 113:
         self.call_exit()
     elif cv_key == 118:
         self.call_default_view()
     elif cv_key == 102:
         self.call_toggle_fitgeom()
     elif cv_key == 50:
         self.call_toggle_2d()
     elif cv_key == 51:
         self.call_toggle_3d()
     elif cv_key == 99:
         self.call_toggle_targetcolor()
     elif cv_key == 100:
         self.call_toggle_apply_fit()
     elif cv_key == 97:
         self.call_toggle_auto_mode()
     elif cv_key != -1:
         print(cv_key)
예제 #15
0
def findRectangularWellsArea(frame, videoPath, hyperparameters):
  
  frame2 = frame.copy()
  
  root = tk.Tk()
  horizontal = root.winfo_screenwidth()
  vertical   = root.winfo_screenheight()
  getRealValueCoefX = 1
  getRealValueCoefY = 1
  if len(frame2[0]) > horizontal or len(frame2) > vertical:
    getRealValueCoefX = len(frame2[0]) / int(horizontal*0.8)
    getRealValueCoefY = len(frame2) / int(vertical*0.8)
    frame2 = cv2.resize(frame2, (int(horizontal*0.8), int(vertical*0.8)))
  root.destroy()
  
  WINDOW_NAME = "Click on the top left of one of the wells"
  cvui.init(WINDOW_NAME)
  cv2.moveWindow(WINDOW_NAME, 0,0)
  cvui.imshow(WINDOW_NAME, frame2)
  while not(cvui.mouse(cvui.CLICK)):
    cursor = cvui.mouse()
    if cv2.waitKey(20) == 27:
      break
  topLeft = [cursor.x, cursor.y]
  cv2.destroyAllWindows()
  
  WINDOW_NAME = "Click on the bottom right of the same well"
  cvui.init(WINDOW_NAME)
  cv2.moveWindow(WINDOW_NAME, 0,0)
  cvui.imshow(WINDOW_NAME, frame2)
  while not(cvui.mouse(cvui.CLICK)):
    cursor = cvui.mouse()
    if cv2.waitKey(20) == 27:
      break
  bottomRight = [cursor.x, cursor.y]
  cv2.destroyAllWindows()  
  
  rectangularWellsArea = int(abs((topLeft[0] - bottomRight[0]) * getRealValueCoefX) * abs((topLeft[1] - bottomRight[1]) * getRealValueCoefY))
  
  return rectangularWellsArea
예제 #16
0
def compact(name):
	# Create a frame for this window and fill it with a nice color
	frame = np.zeros((200, 500, 3), np.uint8)
	frame[:] = (49, 52, 49)

	# Inform cvui that the components to be rendered from now one belong to
	# a window in particular.
	#
	# If you don't inform that, cvui will assume the components belong to
	# the default window (informed in cvui.init()). In that case, the
	# interactions with all other windows being used will not work.
	cvui.context(name)

	cvui.printf(frame, 110, 50, '%s - click the button', name)
	if cvui.button(frame, 110, 90, 'Button'):
		cvui.printf(frame, 200, 95, 'Button clicked!')
		print('Button clicked on: ', name)

	# Tell cvui to update its internal structures regarding a particular window
	# then show it. Below we are using cvui.imshow(), which is cvui's version of
	# the existing cv2.imshow(). They behave exactly the same, the only difference
	# is that cvui.imshow() will automatically call cvui.update(name) for you.
	cvui.imshow(name, frame)
예제 #17
0
        cvui.space(5)
        if cvui.button('&Save'):
            Thread(target=saveimg, args=(image, file_path)).start()
    cvui.endRow()
    cvui.space(10)
    cvui.text(getperc() + '%', 0.8)
    cvui.space(10)
    cvui.endColumn()
    if startFlag and outcnt == sumcnt:
        fps = cap.get(cv2.CAP_PROP_FPS)
        vw = None
        print((Size[0], Size[1]))
        vw = cv2.VideoWriter("out.avi", cv2.VideoWriter_fourcc(*'XVID'), fps,
                             (Size[1], Size[0]), True)
        print(vw.isOpened())
        for i in range(sumcnt):
            # cv2.imshow("origin", toframs[i])
            vw.write(toframs[i])
        vw.release()
        startFlag = False
        print("ok")
    if exitFlag:
        exitflag = False
        cv2.imshow("origin", imag)
        cv2.imshow("final", imgfinal)
        cv2.imshow("edges", edgemap)
        cv2.imshow("anchors", imgx)
    cvui.imshow(WINDOW_NAME, frame)
    if cv2.waitKey(20) == 27:
        break
def main():
    # We have one mat for each window.
    frame1 = np.zeros((200, 500, 3), np.uint8)
    frame2 = np.zeros((200, 500, 3), np.uint8)
    frame3 = np.zeros((200, 500, 3), np.uint8)

    # Init cvui, instructing it to create 3 OpenCV windows.
    windows = [WINDOW1_NAME, WINDOW2_NAME, WINDOW3_NAME]
    cvui.init(windows, 3)

    while (True):
        # clear all frames
        frame1[:] = (49, 52, 49)
        frame2[:] = (49, 52, 49)
        frame3[:] = (49, 52, 49)

        # Inform cvui that all subsequent component calls and events are related to window 1.
        # We do that by calling cvui.context().
        cvui.context(WINDOW1_NAME)
        cvui.printf(
            frame1, 10, 10,
            'In window1, mouse is at: %d,%d (obtained from window name)',
            cvui.mouse(WINDOW1_NAME).x,
            cvui.mouse(WINDOW1_NAME).y)
        if cvui.mouse(WINDOW1_NAME, cvui.LEFT_BUTTON, cvui.IS_DOWN):
            cvui.printf(frame1, 10, 30,
                        'In window1, mouse LEFT_BUTTON is DOWN')
        cvui.imshow(WINDOW1_NAME, frame1)

        # From this point on, we are going to render the second window. We need to inform cvui
        # that all updates and components from now on are connected to window 2.
        cvui.context(WINDOW2_NAME)
        cvui.printf(frame2, 10, 10,
                    'In window2, mouse is at: %d,%d (obtained from context)',
                    cvui.mouse().x,
                    cvui.mouse().y)
        if cvui.mouse(cvui.LEFT_BUTTON, cvui.IS_DOWN):
            cvui.printf(frame2, 10, 30,
                        'In window2, mouse LEFT_BUTTON is DOWN')
        cvui.imshow(WINDOW2_NAME, frame2)

        # Finally we are going to render the thrid window. Again we need to inform cvui
        # that all updates and components from now on are connected to window 3.
        cvui.context(WINDOW3_NAME)
        cvui.printf(frame3, 10, 10, 'In window1, mouse is at: %d,%d',
                    cvui.mouse(WINDOW1_NAME).x,
                    cvui.mouse(WINDOW1_NAME).y)
        cvui.printf(frame3, 10, 30, 'In window2, mouse is at: %d,%d',
                    cvui.mouse(WINDOW2_NAME).x,
                    cvui.mouse(WINDOW2_NAME).y)
        cvui.printf(frame3, 10, 50, 'In window3, mouse is at: %d,%d',
                    cvui.mouse(WINDOW3_NAME).x,
                    cvui.mouse(WINDOW3_NAME).y)
        if cvui.mouse(WINDOW1_NAME, cvui.LEFT_BUTTON, cvui.IS_DOWN):
            cvui.printf(frame3, 10, 90, 'window1: LEFT_BUTTON is DOWN')
        if cvui.mouse(WINDOW2_NAME, cvui.LEFT_BUTTON, cvui.IS_DOWN):
            cvui.printf(frame3, 10, 110, 'window2: LEFT_BUTTON is DOWN')
        if cvui.mouse(WINDOW3_NAME, cvui.LEFT_BUTTON, cvui.IS_DOWN):
            cvui.printf(frame3, 10, 130, 'window3: LEFT_BUTTON is DOWN')
        cvui.imshow(WINDOW3_NAME, frame3)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
def chooseVideoToTroubleshootSplitVideo(self, controller):

  # Choosing video to split

  if globalVariables["mac"]:
    self.videoToTroubleshootSplitVideo = filedialog.askopenfilename(initialdir = os.path.expanduser("~"),title = "Select video")
  else:
    self.videoToTroubleshootSplitVideo = filedialog.askopenfilename(initialdir = os.path.expanduser("~"),title = "Select video",filetypes = (("video","*.*"),("all files","*.*")))
  
  # User input of beginning and end of subvideo
  
  firstFrame = 1
  lastFrame  = 1000
  
  cap = cv2.VideoCapture(self.videoToTroubleshootSplitVideo)
  max_l = int(cap.get(7)) - 2
  
  cap.set(1, 1)
  ret, frame = cap.read()
  WINDOW_NAME = "Choose where the beginning of your sub-video should be."
  WINDOW_NAME_CTRL = "Control"
  cvui.init(WINDOW_NAME)
  cv2.moveWindow(WINDOW_NAME, 0,0)
  cvui.init(WINDOW_NAME_CTRL)
  cv2.moveWindow(WINDOW_NAME_CTRL, 0, 300)
  value = [1]
  curValue = value[0]
  buttonclicked = False
  widgetX = 40
  widgetY = 20
  widgetL = 300
  while not(buttonclicked):
      value[0] = int(value[0])
      if curValue != value[0]:
        cap.set(1, value[0])
        frameOld = frame
        ret, frame = cap.read()
        if not(ret):
          frame = frameOld
        curValue = value[0]
      frameCtrl = np.full((200, 750), 100).astype('uint8')
      frameCtrl[widgetY:widgetY+60, widgetX:widgetX+widgetL] = 0
      cvui.text(frameCtrl, widgetX, widgetY, 'Frame')
      cvui.trackbar(frameCtrl, widgetX, widgetY+10, widgetL, value, 0, max_l)
      cvui.counter(frameCtrl, widgetX, widgetY+60, value)
      buttonclicked = cvui.button(frameCtrl, widgetX, widgetY+90, "Ok, I want the sub-video to start at this frame!")
      
      cvui.text(frameCtrl, widgetX, widgetY+130, 'Keys: 4 or a: move backwards; 6 or d: move forward')
      cvui.text(frameCtrl, widgetX, widgetY+160, 'Keys: g or f: fast backwards; h or j: fast forward')
      cvui.imshow(WINDOW_NAME, frame)
      cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)
      r = cv2.waitKey(20)
      if (r == 54) or (r == 100) or (r == 0):
        value[0] = value[0] + 1
      elif (r == 52) or (r == 97) or (r == 113):
        value[0] = value[0] - 1
      elif (r == 103):
        value[0] = value[0] - 30
      elif (r == 104):
        value[0] = value[0] + 30
      elif (r == 102):
        value[0] = value[0] - 100
      elif (r == 106):
        value[0] = value[0] + 100
  cv2.destroyAllWindows()
  
  firstFrame = int(value[0])
  cap.set(1, max_l)
  ret, frame = cap.read()
  while not(ret):
    max_l = max_l - 1
    cap.set(1, max_l)
    ret, frame = cap.read()
  WINDOW_NAME = "Choose where the sub-video should end."
  WINDOW_NAME_CTRL = "Control"
  cvui.init(WINDOW_NAME)
  cv2.moveWindow(WINDOW_NAME, 0,0)
  cvui.init(WINDOW_NAME_CTRL)
  cv2.moveWindow(WINDOW_NAME_CTRL, 0, 300)
  value = [max_l]
  curValue = value[0]
  buttonclicked = False
  widgetX = 40
  widgetY = 20
  widgetL = 300
  while not(buttonclicked):
      value[0] = int(value[0])
      if curValue != value[0]:
        cap.set(1, value[0])
        frameOld = frame
        ret, frame = cap.read()
        if not(ret):
          frame = frameOld
        curValue = value[0]
      frameCtrl = np.full((200, 400), 100).astype('uint8')
      frameCtrl[widgetY:widgetY+60, widgetX:widgetX+widgetL] = 0
      cvui.text(frameCtrl, widgetX, widgetY, 'Frame')
      cvui.trackbar(frameCtrl, widgetX, widgetY+10, widgetL, value, firstFrame + 1, max_l-1)
      cvui.counter(frameCtrl, widgetX, widgetY+60, value)
      buttonclicked = cvui.button(frameCtrl, widgetX, widgetY+90, "Ok, I want the sub-video to end at this frame!")
      cvui.text(frameCtrl, widgetX, widgetY+130, 'Keys: 4 or a: move backwards; 6 or d: move forward')
      cvui.text(frameCtrl, widgetX, widgetY+160, 'Keys: g or f: fast backwards; h or j: fast forward')
      cvui.imshow(WINDOW_NAME, frame)
      cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)
      r = cv2.waitKey(20)
      if (r == 54) or (r == 100) or (r == 0):
        value[0] = value[0] + 1
      elif (r == 52) or (r == 97) or (r == 113):
        value[0] = value[0] - 1
      elif (r == 103):
        value[0] = value[0] - 30
      elif (r == 104):
        value[0] = value[0] + 30
      elif (r == 102):
        value[0] = value[0] - 100
      elif (r == 106):
        value[0] = value[0] + 100
  
  lastFrame = int(value[0])
  cv2.destroyAllWindows()
  cap.release()
  
  # Choosing directory to save sub-video
  directoryChosen = filedialog.askdirectory(title='Choose in which folder you want to save the sub-video.')
  
  # Extracting sub-video

  cap = cv2.VideoCapture(self.videoToTroubleshootSplitVideo)
  if (cap.isOpened()== False): 
    print("Error opening video stream or file")
    
  frame_width  = int(cap.get(3))
  frame_height = int(cap.get(4))
  xmin = 0
  xmax = frame_width
  ymin = 0
  ymax = frame_height

  out = cv2.VideoWriter(os.path.join(directoryChosen, 'subvideo.avi'), cv2.VideoWriter_fourcc('M','J','P','G'), 10, (xmax-xmin,ymax-ymin))
   
  i = firstFrame
  maxx = lastFrame
  cap.set(1, i)
  while(cap.isOpened() and (i<maxx)):
    i = i + 1
    ret, frame = cap.read()
    if ret == True:
      frame2 = frame[ymin:ymax,xmin:xmax]
      if False:
        frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
        frame2 = cv2.cvtColor(frame2, cv2.COLOR_GRAY2BGR)
      out.write(frame2)
    else: 
      break
  cap.release()

  self.show_frame("VideoToTroubleshootSplitVideo")
예제 #20
0
def main(toml_path, directory_for_save, save_raw_data, scale, timelapse_mode,
         interval_minute):
    make_save_dir(directory_for_save)
    see3cam_mng = RgbCameraManager(toml_path)
    lens_undistorter = LensUndistorter(toml_path)
    scaling = partial(scaling_int, scale=scale)

    WINDOW_NAME = "Capture"
    cvui.init(WINDOW_NAME)
    while True:
        key = cv2.waitKey(10)
        frame = np.zeros((scaling(960), scaling(1400), 3), np.uint8)
        frame[:] = (49, 52, 49)

        status = see3cam_mng.update()

        number_of_saved_frame = len(
            glob.glob(os.path.join(directory_for_save, "*.png")))
        cvui.printf(frame, 50, scaling(750), 0.8, 0x00FF00,
                    "Number of Captured Images : %d", number_of_saved_frame)

        if status:
            see3cam_rgb_image_raw = see3cam_mng.read()
            see3cam_rgb_image_undist = lens_undistorter.correction(
                see3cam_rgb_image_raw)
            scaled_width = scaling(1280)
            scaled_height = scaling(720)
            see3cam_rgb_resize = cv2.resize(see3cam_rgb_image_undist,
                                            (scaled_width, scaled_height))

            cvui.text(frame, 10, 10, "See3CAM", 0.5)
            frame[10:scaled_height + 10,
                  10:scaled_width + 10, :] = see3cam_rgb_resize

            # For time lapse capturing
            capture_condition = cvui.button(
                frame, 50, scaling(800), 200, 100,
                "capture image") or key & 0xFF == ord("s")
            if timelapse_mode:
                current_time = datetime.now()
                if current_time.minute % interval_minute == 0 and current_time.second % 60 == 0:
                    print("captured:{}, time:{}".format(
                        number_of_saved_frame, current_time))
                    capture_condition = True

            if capture_condition:
                if status:
                    if save_raw_data:
                        save_image(see3cam_rgb_image_raw, directory_for_save)
                    else:
                        save_image(see3cam_rgb_image_undist,
                                   directory_for_save)

            if timelapse_mode:
                time.sleep(1)

            if cvui.button(frame, 300, scaling(800), 200, 100, "erase"):
                clean_save_dir(directory_for_save)

        if key == 27 or key == ord("q"):
            break

        cvui.update()
        cvui.imshow(WINDOW_NAME, frame)
    cv2.destroyAllWindows()
예제 #21
0
def prepareConfigFileForParamsAdjustements(configFile, wellNumber, firstFrameParamAdjust, videoToCreateConfigFileFor, adjustOnWholeVideo):
  
  initialFirstFrameValue = -1
  initialLastFrameValue  = -1
  if "firstFrame" in configFile:
    initialFirstFrameValue = configFile["firstFrame"]
  if "lastFrame" in configFile:
    initialLastFrameValue  = configFile["lastFrame"]
  
  cap = cv2.VideoCapture(videoToCreateConfigFileFor)
  max_l = int(cap.get(7))
  if int(firstFrameParamAdjust):
    cap.set(1, 1)
    ret, frame = cap.read()
    WINDOW_NAME = "Choose where you want to start the procedure to adjust parameters."
    WINDOW_NAME_CTRL = "Control"
    cvui.init(WINDOW_NAME)
    cv2.moveWindow(WINDOW_NAME, 0,0)
    cvui.init(WINDOW_NAME_CTRL)
    cv2.moveWindow(WINDOW_NAME_CTRL, 0, 300)
    value = [1]
    curValue = value[0]
    buttonclicked = False
    widgetX = 40
    widgetY = 50
    widgetL = 300
    while not(buttonclicked):
      value[0] = int(value[0])
      if curValue != value[0]:
        cap.set(1, value[0])
        frameOld = frame
        ret, frame = cap.read()
        if not(ret):
          frame = frameOld
        curValue = value[0]
      frameCtrl = np.full((200, 400), 100).astype('uint8')
      frameCtrl[widgetY:widgetY+60, widgetX:widgetX+widgetL] = 0
      cvui.text(frameCtrl, widgetX, widgetY, 'Frame')
      cvui.trackbar(frameCtrl, widgetX, widgetY+10, widgetL, value, 0, max_l-1)
      cvui.counter(frameCtrl, widgetX, widgetY+60, value)
      buttonclicked = cvui.button(frameCtrl, widgetX, widgetY+90, "Ok, I want the procedure to start at this frame.")
      cvui.text(frameCtrl, widgetX, widgetY+130, 'Keys: 4 or a: move backwards; 6 or d: move forward')
      cvui.text(frameCtrl, widgetX, widgetY+160, 'Keys: g or f: fast backwards; h or j: fast forward')
      cvui.imshow(WINDOW_NAME, frame)
      cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)
      r = cv2.waitKey(20)
      if (r == 54) or (r == 100) or (r == 0):
        value[0] = value[0] + 1
      elif (r == 52) or (r == 97) or (r == 113):
        value[0] = value[0] - 1
      elif (r == 103):
        value[0] = value[0] - 30
      elif (r == 104):
        value[0] = value[0] + 30
      elif (r == 102):
        value[0] = value[0] - 100
      elif (r == 106):
        value[0] = value[0] + 100
    configFile["firstFrame"] = int(value[0])
    cv2.destroyAllWindows()
    if not(int(adjustOnWholeVideo)):
      if ("lastFrame" in configFile):
        if (configFile["lastFrame"] - configFile["firstFrame"] > 500):
          configFile["lastFrame"] = configFile["firstFrame"] + 500
      else:
        configFile["lastFrame"]  = min(configFile["firstFrame"] + 500, max_l-10)
  else:
    if not(int(adjustOnWholeVideo)):
      if ("firstFrame" in configFile) and ("lastFrame" in configFile):
        if configFile["lastFrame"] - configFile["firstFrame"] > 500:
          configFile["lastFrame"] = configFile["firstFrame"] + 500
      else:
        configFile["firstFrame"] = 1
        configFile["lastFrame"]  = min(max_l-10, 500)
  
  if "lastFrame" in configFile:
    if configFile["lastFrame"] > initialLastFrameValue and initialLastFrameValue != -1:
      configFile["lastFrame"] = initialLastFrameValue
  
  if len(wellNumber) != 0:
    configFile["onlyTrackThisOneWell"] = int(wellNumber)
  else:
    configFile["onlyTrackThisOneWell"] = 0
  
  configFile["reloadBackground"] = 1
  
  return [configFile, initialFirstFrameValue, initialLastFrameValue]
예제 #22
0
def main(save_dir):
    make_save_dir(save_dir)
    zense_camera = PyZenseManager()
    pt2_camera = PyPureThermal2()
    image_width, image_height = zense_camera.image_size

    res_image_width = int(image_width * 0.75)
    res_image_height = int(image_height * 0.75)
    window_image_width = int(res_image_width * 3)
    window_image_height = int(res_image_height * 1.5)

    cvui.init("capture")
    frame = np.zeros((window_image_height, window_image_width + 540, 3),
                     np.uint8)
    captured_frame_count = count_images(save_dir)

    while True:
        key = cv2.waitKey(10)
        frame[:] = (49, 52, 49)

        status = zense_camera.update(verbose=UPDATE_VERBOSE)
        status &= pt2_camera.update()
        if status:
            # Get Images
            ir_image = zense_camera.ir_image.copy()
            depth_image = zense_camera.depth_image.copy()

            thermal_image = pt2_camera.thermal_image.copy()
            thermal_image_colorized = pt2_camera.thermal_image_colorized.copy()

            # Visualize Images
            frame = draw_frames(frame, depth_image, ir_image,
                                thermal_image_colorized, res_image_width,
                                res_image_height)
            if cvui.button(frame, 50, window_image_height - 50, 130, 50,
                           "Save Result Image") or key & 0xFF == ord("s"):
                save_images(
                    depth_image,
                    ir_image,
                    thermal_image,
                    thermal_image_colorized,
                    save_dir,
                )
                captured_frame_count += 1

            if cvui.button(frame, 200, window_image_height - 50, 130, 50,
                           "Clear"):
                clean_save_dir(save_dir)
                captured_frame_count = 0

            cvui.printf(
                frame,
                900,
                window_image_height - 30,
                0.8,
                0x00FF00,
                "Number of Captured Images : %d",
                captured_frame_count,
            )
            if key & 0xFF == ord("q"):
                break

            cvui.update()
            cvui.imshow("capture", frame)

    cv2.destroyAllWindows()
예제 #23
0
def identifyMultipleHead(self, controller, nbanimals):

    self.configFile["videoName"] = "configFilePrep"

    tempConfig = self.configFile

    horizontal = self.winfo_screenwidth()
    vertical = self.winfo_screenheight()

    # Wait image
    WINDOW_NAME = "Please Wait"
    cv2.destroyAllWindows()
    cvui.init(WINDOW_NAME)
    cv2.moveWindow(WINDOW_NAME, 0, 0)
    # Getting hyperparameters, wellPositions, and background
    hyperparameters = getHyperparametersSimple(tempConfig)
    wellPositions = findWells(self.videoToCreateConfigFileFor, hyperparameters)
    background = getBackground(self.videoToCreateConfigFileFor,
                               hyperparameters)

    cur_dir_path = os.path.dirname(os.path.realpath(__file__))
    cur_dir_path = Path(cur_dir_path)

    tab = [1]
    img = cv2.imread(os.path.join(cur_dir_path, 'no1.png'))
    img = cv2.resize(img, (int(horizontal * 0.95), int(vertical * 0.8)))
    buttonclicked = False
    count = 0
    while not (buttonclicked):
        buttonclicked = cvui.button(img, 10, 10, "Ok, I understand!")
        cvui.imshow(WINDOW_NAME, img)
        cv2.waitKey(20)
        count = count + 1
        if count > 100:
            buttonclicked = True
    img = cv2.imread(os.path.join(cur_dir_path, 'no2.png'))
    img = cv2.resize(img, (int(horizontal * 0.95), int(vertical * 0.8)))
    buttonclicked = False
    count = 0
    while not (buttonclicked):
        buttonclicked = cvui.button(img, 10, 10, "Ok, I understand!")
        cvui.imshow(WINDOW_NAME, img)
        cv2.waitKey(20)
        count = count + 1
        if count > 100:
            buttonclicked = True
    img = cv2.imread(os.path.join(cur_dir_path, 'ok1.png'))
    img = cv2.resize(img, (int(horizontal * 0.95), int(vertical * 0.8)))
    buttonclicked = False
    count = 0
    while not (buttonclicked):
        buttonclicked = cvui.button(img, 10, 10, "Ok, I understand!")
        cvui.imshow(WINDOW_NAME, img)
        cv2.waitKey(20)
        count = count + 1
        if count > 100:
            buttonclicked = True

    WINDOW_NAME = "Adjust Parameters: As much as possible, you must see red points on and only on animals on the right image."
    WINDOW_NAME_CTRL = "Adjust Parameters."
    cv2.destroyAllWindows()
    # Manual parameters adjustements
    cap = cv2.VideoCapture(self.videoToCreateConfigFileFor)
    nx = int(cap.get(3))
    ny = int(cap.get(4))
    max_l = int(cap.get(7))

    hyperparameters["minArea"] = 5
    hyperparameters["maxArea"] = 800

    [frame, maxAreaBlobs
     ] = getImageForMultipleAnimalGUI(1, vertical, horizontal, nx, ny, max_l,
                                      self.videoToCreateConfigFileFor,
                                      background, wellPositions,
                                      hyperparameters)
    frameCtrl = np.full((200, 1100), 100).astype('uint8')

    cvui.init(WINDOW_NAME)
    cv2.moveWindow(WINDOW_NAME, 0, 0)
    cvui.imshow(WINDOW_NAME, frame)

    cvui.init(WINDOW_NAME_CTRL)
    cv2.moveWindow(WINDOW_NAME_CTRL, 0, vertical - 290)
    cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)

    frameNum = [hyperparameters["firstFrame"]
                ] if "firstFrame" in hyperparameters else [1]
    curFrameNum = frameNum[0] + 1
    minPixelDiffForBackExtract = [
        hyperparameters["minPixelDiffForBackExtract"]
    ]
    thresholdForBlobImg = [hyperparameters["thresholdForBlobImg"]]
    dilateIter = [hyperparameters["dilateIter"]]
    minArea = [hyperparameters["minArea"]]
    maxArea = [hyperparameters["maxArea"]]
    firstFrame = hyperparameters[
        "firstFrame"] if "firstFrame" in hyperparameters else 1
    lastFrame = hyperparameters[
        "lastFrame"] - 1 if "lastFrame" in hyperparameters else max_l - 10

    buttonclicked = False
    while not (buttonclicked):
        if curFrameNum != frameNum[0] or hyperparameters[
                "minPixelDiffForBackExtract"] != minPixelDiffForBackExtract[
                    0] or hyperparameters[
                        "thresholdForBlobImg"] != thresholdForBlobImg[
                            0] or hyperparameters["dilateIter"] != dilateIter[
                                0] or hyperparameters["minArea"] != minArea[
                                    0] or hyperparameters[
                                        "maxArea"] != maxArea[0]:

            curFrameNum = frameNum[0]
            hyperparameters["minPixelDiffForBackExtract"] = int(
                minPixelDiffForBackExtract[0])
            hyperparameters["thresholdForBlobImg"] = int(
                thresholdForBlobImg[0])
            hyperparameters["dilateIter"] = int(dilateIter[0])
            hyperparameters["minArea"] = int(minArea[0])
            hyperparameters["maxArea"] = int(maxArea[0])

            [frame, maxAreaBlobs] = getImageForMultipleAnimalGUI(
                curFrameNum, vertical, horizontal, nx, ny, max_l,
                self.videoToCreateConfigFileFor, background, wellPositions,
                hyperparameters)

        frameCtrl = np.full((200, 1100), 100).astype('uint8')

        printStuffOnCtrlImg(frameCtrl, frameNum, 1, 5, 350, firstFrame,
                            lastFrame, "Frame number")
        printStuffOnCtrlImg(frameCtrl, minPixelDiffForBackExtract, 470, 5, 350,
                            0, 255, "Threshold left image")
        printStuffOnCtrlImg(frameCtrl, thresholdForBlobImg, 1, 71, 350, 0, 255,
                            "Threshold right image")
        printStuffOnCtrlImg(frameCtrl, dilateIter, 470, 71, 350, 0, 15,
                            "Area dilatation")
        printStuffOnCtrlImg(frameCtrl, minArea, 1, 137, 350, 0, maxAreaBlobs,
                            "Minimum area")
        printStuffOnCtrlImg(frameCtrl, maxArea, 470, 137, 350, 0, maxAreaBlobs,
                            "Maximum area")

        buttonclicked = cvui.button(frameCtrl, 940, 10, "Ok, done!")

        cvui.imshow(WINDOW_NAME, frame)
        cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)

        if cv2.waitKey(20) == 27:
            break
    cv2.destroyAllWindows()

    del self.configFile["videoName"]

    self.configFile["minPixelDiffForBackExtract"] = int(
        hyperparameters["minPixelDiffForBackExtract"])
    self.configFile["thresholdForBlobImg"] = int(
        hyperparameters["thresholdForBlobImg"])
    self.configFile["dilateIter"] = int(hyperparameters["dilateIter"])
    self.configFile["minArea"] = int(hyperparameters["minArea"])
    self.configFile["maxArea"] = int(hyperparameters["maxArea"])
    self.configFile["headSize"] = math.sqrt(
        (int(hyperparameters["minArea"]) + int(hyperparameters["maxArea"])) /
        2)
        print('Start recording')

        fps = FPS().start()
        while GPIO.input(rec_channel):
            start = time.time()
            image = vs.read()
            fps.update()

            data_storage.append(image[None])
            sttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
            logFile.write(str(fps._numFrames) + '\t' + sttime + '\n')

            #cvui.sparkline(combined, fpsHist, 0, 0, 400, 200);

            #cv2.imshow("combined", combined)
            cvui.imshow(WINDOW_NAME, image)
            cv2.waitKey(1)

            time.sleep(max(1. / fr - (time.time() - start), 0))

        image_hdf5_file.close()
        logFile.close()
        fps.stop()
        print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
        print("[INFO] approx. FPS: {:.2f}\n\n".format(fps.fps()))
        writer.writerow({
            'mouse_id': mouse_id,
            'data_path': data_dir,
            'start': fps._start,
            'end': fps._end,
            'fps': fps.fps()
예제 #25
0
    def onWork(self):
        self.frame[:] = (49, 52, 49)
        char = cv.waitKey(1)

        doOverw = False

        writeOnName = False
        writeOnSubject = False
        writeOnProf = False

        stringCopy = ''
        stringCopyColor = 0x10dca1

        while True:

            cursor = cvui.mouse(WINDOW_NAME)
            click = cvui.mouse(cvui.CLICK)

            # (self, x, y, w, h, title, char, writeOn, cursor, click, writeOnBool):
            writeOnName, self.folderName = self.textInput(
                5, 5, 305, 40, "Folder Name:", char, self.folderName, cursor,
                click, writeOnName)

            writeOnSubject, self.subjectName = self.textInput(
                5 + X_SCREEN / 2, 5, 305, 40, "Subject Name:", char,
                self.subjectName, cursor, click, writeOnSubject)

            writeOnProf, self.tempName = self.textInput(
                5 + X_SCREEN / 2, 105, 305, 40, "Professors:", char,
                self.tempName, cursor, click, writeOnProf)
            cvui.rect(self.frame, 6 + X_SCREEN / 2, 155, X_SCREEN / 2 - 63,
                      235 - 165, 0x8d9797, 0x3c4747)
            cvui.rect(self.frame, X_SCREEN - 52, 155, 47, 235 - 165, 0x8d9797,
                      0x293939)
            if cvui.button(
                    self.frame, X_SCREEN - 49, 157,
                    "+") and not self.tempName == '' and len(self.names) < 4:
                self.names.append(self.tempName)
                self.tempName = ''
            if cvui.button(self.frame, X_SCREEN - 49, 196,
                           "-") and not len(self.names) == 0:
                del self.names[-1]

            for i in range(len(self.names)):
                cvui.printf(self.frame, 10 + X_SCREEN / 2, 160 + 15 * i, 0.4,
                            0xdd97fb, self.names[i])

            xp = int((X_SCREEN - 20) / 4)

            cvui.window(self.frame, 5, 235, X_SCREEN - 10, Y_SCREEN - 235 - 5,
                        "Premade:")
            if cvui.button(self.frame, 10 + xp - 10 * 11, 260, "Lab. Micro."):
                self.subjectName = '22.99 Laboratorio De Microprocesadores'
                self.names.clear()
                self.names.append('Jacoby, Daniel Andres')
                self.names.append('Magliola, Nicolas')
                self.names.append('Ismirlian, Diego Matias')
                self.group[0] = 3

            if cvui.button(self.frame, 10 + xp * 2 - 10 * 7, 260, "Control"):
                self.subjectName = '22.85 Sistemas de Control'
                self.names.clear()
                self.names.append('Nasini, Victor Gustavo')
                self.names.append('Zujew, Cristian Alejo')

            if cvui.button(self.frame, 10 + xp * 3 - 10 * 9, 260, "Transinfo"):
                self.subjectName = '22.61 Transmision de la Informacion'
                self.names.clear()
                self.names.append('Bertucci, Eduardo Adolfo')
                self.names.append('Vila Krause, Luis Gustavo')

            if cvui.button(self.frame, 10 + xp * 4 - 10 * 11, 260,
                           "Electromag."):
                self.subjectName = '22.37 Electromagnetismo'
                self.names.clear()
                self.names.append('Munoz, Claudio Marcelo')
                self.names.append('Dobrusin, Pablo')

            cvui.printf(self.frame, 5, 55, 0.4, 0xdd97fb, f'N Exercises:')
            cvui.counter(self.frame, 5, 70, self.numberFolder)
            if self.numberFolder[0] <= 0:
                cvui.rect(self.frame, 5 + 25, 72, 40, 17, 0x292929, 0x292929)
                self.numberFolder[0] = 1
                cvui.printf(self.frame, 5 + 41, 76, 0.4, 0x9C9C9C, '1')

            cvui.printf(self.frame, 5 + X_SCREEN / 6, 55, 0.4, 0xdd97fb,
                        f'Day:')
            cvui.counter(self.frame, 5 + X_SCREEN / 6, 70, self.day)
            if self.day[0] <= 0:
                cvui.rect(self.frame, 5 + X_SCREEN / 6 + 25, 72, 40, 17,
                          0x292929, 0x292929)
                self.day[0] = 1
                cvui.printf(self.frame, 5 + X_SCREEN / 6 + 41, 76, 0.4,
                            0x9C9C9C, '1')
            elif self.day[0] >= 31:
                self.day[0] = 31

            cvui.printf(self.frame, 5 + X_SCREEN * 2 / 6, 55, 0.4, 0xdd97fb,
                        f'Month:')
            cvui.counter(self.frame, 5 + X_SCREEN * 2 / 6, 70, self.month)
            if self.month[0] <= 0:
                cvui.rect(self.frame, 5 + X_SCREEN * 2 / 6 + 25, 72, 40, 17,
                          0x292929, 0x292929)
                self.month[0] = 1
                cvui.printf(self.frame, 5 + X_SCREEN * 2 / 6 + 41, 76, 0.4,
                            0x9C9C9C, '1')
            elif self.month[0] >= 12:
                self.month[0] = 12

            cvui.printf(self.frame, 5 + X_SCREEN * 3 / 6, 55, 0.4, 0xdd97fb,
                        f'Year:')
            cvui.counter(self.frame, 5 + X_SCREEN * 3 / 6, 70, self.year)
            if self.year[0] <= 19:
                cvui.rect(self.frame, 5 + X_SCREEN * 3 / 6 + 25, 72, 40, 17,
                          0x292929, 0x292929)
                self.year[0] = 20
                cvui.printf(self.frame, 5 + X_SCREEN * 3 / 6 + 37, 76, 0.4,
                            0x9C9C9C, '20')
            elif self.year[0] >= 22:
                self.year[0] = 22

            cvui.printf(self.frame, 5 + X_SCREEN * 4 / 6, 55, 0.4, 0xdd97fb,
                        f'N Group:')
            cvui.counter(self.frame, 5 + X_SCREEN * 4 / 6, 70, self.group)
            if self.group[0] <= 0:
                cvui.rect(self.frame, 5 + X_SCREEN * 4 / 6 + 25, 72, 40, 17,
                          0x292929, 0x292929)
                self.group[0] = 1
                cvui.printf(self.frame, 5 + X_SCREEN * 4 / 6 + 41, 76, 0.4,
                            0x9C9C9C, '1')
            elif self.group[0] >= 7:
                self.group[0] = 7

            cvui.printf(self.frame, 5 + X_SCREEN * 5 / 6, 55, 0.4, 0xdd97fb,
                        f'N TP:')
            cvui.counter(self.frame, 5 + X_SCREEN * 5 / 6, 70, self.tp)
            if self.tp[0] <= 0:
                cvui.rect(self.frame, 5 + X_SCREEN * 5 / 6 + 25, 72, 40, 17,
                          0x292929, 0x292929)
                self.tp[0] = 1
                cvui.printf(self.frame, 5 + X_SCREEN * 5 / 6 + 41, 76, 0.4,
                            0x9C9C9C, '1')

            if cvui.button(self.frame, X_SCREEN / 4 - 10 * 16 / 2, 110,
                           "Load Folder Path") and not doOverw:
                self.folderPath = self.getPath()

            cvui.window(self.frame, 5, 155, X_SCREEN / 2 - 10, 40,
                        "Folder Path Selected")
            if len(self.folderPath) < MAXCHAR + 3:
                cvui.printf(self.frame, 10, 180, 0.4, 0xdd97fb,
                            self.folderPath)
            else:
                cvui.printf(self.frame, 10, 180, 0.4, 0xdd97fb,
                            self.folderPath[0:MAXCHAR + 2] + '...')

            if (not self.folderPath
                    == '') and (not self.folderName
                                == '') and (not self.subjectName == ''):
                if cvui.button(self.frame, 120, 200, "Start Copy"):
                    self.startCopy = True
                    stringCopy = "Wait While Copying..."
                    stringCopyColor = 0xdc1076

            cvui.printf(self.frame, 5, 205, 0.4, stringCopyColor, stringCopy)

            if self.startCopy:
                self.startCopy = False

                while self.folderName[-1] == ' ':  #32:
                    self.folderName = self.folderName[:-1]

                finalPath = self.folderPath + '/' + self.folderName

                coping = self.copyFolders(self.numberFolder[0], finalPath,
                                          True)

                if not coping == None:
                    if not coping:
                        doOverw = True
                    else:
                        stringCopy = "Copy Done!"
                        stringCopyColor = 0x10dca1
                else:
                    stringCopy = "Template Not Found!!"
                    stringCopyColor = 0xdc1076

            if doOverw:
                check = self.overWrite(finalPath)
                if not check == -1:
                    if check == None:
                        stringCopy = "Template Not Found!!"
                        stringCopyColor = 0xdc1076
                    else:
                        if check == True:
                            stringCopy = "Copy Done!"
                            stringCopyColor = 0x10dca1
                        else:
                            stringCopy = "Unable To Copy"
                            stringCopyColor = 0xdc1076
                    doOverw = False

            cvui.imshow(WINDOW_NAME, self.frame)
            char = cv.waitKey(1)
            self.frame[:] = (49, 52, 49)

            if (char == 27) or not cv.getWindowProperty(
                    WINDOW_NAME, cv.WND_PROP_VISIBLE):
                break
예제 #26
0
파일: mouse.py 프로젝트: Dovyski/cvui
def main():
	frame = np.zeros((300, 600, 3), np.uint8)

	# Init cvui and tell it to create a OpenCV window, i.e. cv::namedWindow(WINDOW_NAME).
	cvui.init(WINDOW_NAME);

	# Rectangle to be rendered according to mouse interactions.
	rectangle = cvui.Rect(0, 0, 0, 0)

	while (True):
		# Fill the frame with a nice color
		frame[:] = (49, 52, 49)

		# Show the coordinates of the mouse pointer on the screen
		cvui.text(frame, 10, 30, 'Click (any) mouse button and drag the pointer around to select an area.')
		cvui.printf(frame, 10, 50, 'Mouse pointer is at (%d,%d)', cvui.mouse().x, cvui.mouse().y)

		# The function "bool cvui.mouse(int query)" allows you to query the mouse for events.
		# E.g. cvui.mouse(cvui.DOWN)
		#
		# Available queries:
		#	- cvui.DOWN: any mouse button was pressed. cvui.mouse() returns true for a single frame only.
		#	- cvui.UP: any mouse button was released. cvui.mouse() returns true for a single frame only.
		#	- cvui.CLICK: any mouse button was clicked (went down then up, no matter the amount of frames in between). cvui.mouse() returns true for a single frame only.
		#	- cvui.IS_DOWN: any mouse button is currently pressed. cvui.mouse() returns true for as long as the button is down/pressed.

		# Did any mouse button go down?
		if cvui.mouse(cvui.DOWN):
			# Position the rectangle at the mouse pointer.
			rectangle.x = cvui.mouse().x
			rectangle.y = cvui.mouse().y

		# Is any mouse button down (pressed)?
		if cvui.mouse(cvui.IS_DOWN):
			# Adjust rectangle dimensions according to mouse pointer
			rectangle.width = cvui.mouse().x - rectangle.x
			rectangle.height = cvui.mouse().y - rectangle.y

			# Show the rectangle coordinates and size
			cvui.printf(frame, rectangle.x + 5, rectangle.y + 5, 0.3, 0xff0000, '(%d,%d)', rectangle.x, rectangle.y)
			cvui.printf(frame, cvui.mouse().x + 5, cvui.mouse().y + 5, 0.3, 0xff0000, 'w:%d, h:%d', rectangle.width, rectangle.height)

		# Did any mouse button go up?
		if cvui.mouse(cvui.UP):
			# Hide the rectangle
			rectangle.x = 0
			rectangle.y = 0
			rectangle.width = 0
			rectangle.height = 0

		# Was the mouse clicked (any button went down then up)?
		if cvui.mouse(cvui.CLICK):
			cvui.text(frame, 10, 70, 'Mouse was clicked!')

		# Render the rectangle
		cvui.rect(frame, rectangle.x, rectangle.y, rectangle.width, rectangle.height, 0xff0000)

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc, then
		# shows the frame in a window like cv2.imshow() does.
		cvui.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
예제 #27
0
         countflag=1
         time.sleep(2)
         partcount=partcount+1
         serialdata={"count":partcount}
         with open("masterdata/serial.yaml", "w") as f:
             yaml.dump(serialdata, f)
         now=datetime.datetime.now()
         date=str(now.day)+'/'+str(now.month)+'/'+str(now.year)+"  "+str(now.hour)+':'+str(now.minute)+':'+str(now.second)
         count=str(partcount)
         #print("image wrote to",name)
         test=cv2.imread("test.jpg")
         sy="masterdata/ins.png"
         im="test.jpg"
         page()
         page3(date,count,im,sy)
         cvui.imshow(mainwindow, frame1)
         print ("searching")
         prost=1
         camera.LineSelector.SetValue("Line1")
         camera.UserOutputValue.SetValue(False)
     
 if(k==32):
     partcount=partcount+1
     serialdata={"count":partcount}
     with open("masterdata/serial.yaml", "w") as f:
         yaml.dump(serialdata, f)
     serial=serialfromplc()    
     now=datetime.datetime.now()
     date=str(now.day)+'/'+str(now.month)+'/'+str(now.year)+"     "+str(now.hour)+':'+str(now.minute)+':'+str(now.second)
     count=str(partcount)
     #name="savedata/"+str(now.day)+str(now.month)+str(now.year)+"_"+str(now.hour)+"_"+str(now.minute)+"_"+str(now.second)+"f"+str(now.microsecond)+".jpg"
예제 #28
0
def main():
    frame = np.zeros((300, 600, 3), np.uint8)

    # Init cvui and tell it to create a OpenCV window, i.e. cv::namedWindow(WINDOW_NAME).
    cvui.init(WINDOW_NAME)

    # Rectangle to be rendered according to mouse interactions.
    rectangle = cvui.Rect(0, 0, 0, 0)

    while (True):
        # Fill the frame with a nice color
        frame[:] = (49, 52, 49)

        # Show the coordinates of the mouse pointer on the screen
        cvui.text(
            frame, 10, 30,
            'Click (any) mouse button and drag the pointer around to select an area.'
        )
        cvui.printf(frame, 10, 50, 'Mouse pointer is at (%d,%d)',
                    cvui.mouse().x,
                    cvui.mouse().y)

        # The function "bool cvui.mouse(int query)" allows you to query the mouse for events.
        # E.g. cvui.mouse(cvui.DOWN)
        #
        # Available queries:
        #	- cvui.DOWN: any mouse button was pressed. cvui.mouse() returns true for a single frame only.
        #	- cvui.UP: any mouse button was released. cvui.mouse() returns true for a single frame only.
        #	- cvui.CLICK: any mouse button was clicked (went down then up, no matter the amount of frames in between). cvui.mouse() returns true for a single frame only.
        #	- cvui.IS_DOWN: any mouse button is currently pressed. cvui.mouse() returns true for as long as the button is down/pressed.

        # Did any mouse button go down?
        if cvui.mouse(cvui.DOWN):
            # Position the rectangle at the mouse pointer.
            rectangle.x = cvui.mouse().x
            rectangle.y = cvui.mouse().y

        # Is any mouse button down (pressed)?
        if cvui.mouse(cvui.IS_DOWN):
            # Adjust rectangle dimensions according to mouse pointer
            rectangle.width = cvui.mouse().x - rectangle.x
            rectangle.height = cvui.mouse().y - rectangle.y

            # Show the rectangle coordinates and size
            cvui.printf(frame, rectangle.x + 5, rectangle.y + 5, 0.3, 0xff0000,
                        '(%d,%d)', rectangle.x, rectangle.y)
            cvui.printf(frame,
                        cvui.mouse().x + 5,
                        cvui.mouse().y + 5, 0.3, 0xff0000, 'w:%d, h:%d',
                        rectangle.width, rectangle.height)

        # Did any mouse button go up?
        if cvui.mouse(cvui.UP):
            # Hide the rectangle
            rectangle.x = 0
            rectangle.y = 0
            rectangle.width = 0
            rectangle.height = 0

        # Was the mouse clicked (any button went down then up)?
        if cvui.mouse(cvui.CLICK):
            cvui.text(frame, 10, 70, 'Mouse was clicked!')

        # Render the rectangle
        cvui.rect(frame, rectangle.x, rectangle.y, rectangle.width,
                  rectangle.height, 0xff0000)

        # This function must be called *AFTER* all UI components. It does
        # all the behind the scenes magic to handle mouse clicks, etc, then
        # shows the frame in a window like cv2.imshow() does.
        cvui.imshow(WINDOW_NAME, frame)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
예제 #29
0
def chooseBeginningAndEndOfVideo(self, controller):
    cap = cv2.VideoCapture(self.videoToCreateConfigFileFor)
    max_l = int(cap.get(7)) - 2

    cap.set(1, 1)
    ret, frame = cap.read()
    WINDOW_NAME = "Choose where the analysis of your video should start."
    WINDOW_NAME_CTRL = "Control"
    cvui.init(WINDOW_NAME)
    cv2.moveWindow(WINDOW_NAME, 0, 0)
    cvui.init(WINDOW_NAME_CTRL)
    cv2.moveWindow(WINDOW_NAME_CTRL, 0, 300)
    value = [1]
    curValue = value[0]
    buttonclicked = False
    buttonEntireVideo = False
    widgetX = 40
    widgetY = 20
    widgetL = 300
    while not (buttonclicked) and not (buttonEntireVideo):
        value[0] = int(value[0])
        if curValue != value[0]:
            cap.set(1, value[0])
            frameOld = frame
            ret, frame = cap.read()
            if not (ret):
                frame = frameOld
            curValue = value[0]
        frameCtrl = np.full((200, 750), 100).astype('uint8')
        frameCtrl[widgetY:widgetY + 60, widgetX:widgetX + widgetL] = 0
        cvui.text(frameCtrl, widgetX, widgetY, 'Frame')
        cvui.trackbar(frameCtrl, widgetX, widgetY + 10, widgetL, value, 0,
                      max_l)
        cvui.counter(frameCtrl, widgetX, widgetY + 60, value)
        buttonclicked = cvui.button(
            frameCtrl, widgetX, widgetY + 90,
            "Ok, I want the tracking to start at this frame!")

        cvui.text(frameCtrl, widgetX + 350, widgetY + 1,
                  'No, this is unecessary:')
        buttonEntireVideo = cvui.button(
            frameCtrl, widgetX + 350, widgetY + 40,
            "I want the tracking to run on the entire video!")

        cvui.text(frameCtrl, widgetX, widgetY + 130,
                  'Keys: 4 or a: move backwards; 6 or d: move forward')
        cvui.text(frameCtrl, widgetX, widgetY + 160,
                  'Keys: g or f: fast backwards; h or j: fast forward')
        cvui.imshow(WINDOW_NAME, frame)
        cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)
        r = cv2.waitKey(20)
        if (r == 54) or (r == 100) or (r == 0):
            value[0] = value[0] + 1
        elif (r == 52) or (r == 97) or (r == 113):
            value[0] = value[0] - 1
        elif (r == 103):
            value[0] = value[0] - 30
        elif (r == 104):
            value[0] = value[0] + 30
        elif (r == 102):
            value[0] = value[0] - 100
        elif (r == 106):
            value[0] = value[0] + 100
    cv2.destroyAllWindows()

    if not (buttonEntireVideo):
        self.configFile["firstFrame"] = int(value[0])
        cap.set(1, max_l)
        ret, frame = cap.read()
        while not (ret):
            max_l = max_l - 1
            cap.set(1, max_l)
            ret, frame = cap.read()
        WINDOW_NAME = "Choose where the analysis of your video should end."
        WINDOW_NAME_CTRL = "Control"
        cvui.init(WINDOW_NAME)
        cv2.moveWindow(WINDOW_NAME, 0, 0)
        cvui.init(WINDOW_NAME_CTRL)
        cv2.moveWindow(WINDOW_NAME_CTRL, 0, 300)
        value = [max_l]
        curValue = value[0]
        buttonclicked = False
        widgetX = 40
        widgetY = 20
        widgetL = 300
        while not (buttonclicked):
            value[0] = int(value[0])
            if curValue != value[0]:
                cap.set(1, value[0])
                frameOld = frame
                ret, frame = cap.read()
                if not (ret):
                    frame = frameOld
                curValue = value[0]
            frameCtrl = np.full((200, 400), 100).astype('uint8')
            frameCtrl[widgetY:widgetY + 60, widgetX:widgetX + widgetL] = 0
            cvui.text(frameCtrl, widgetX, widgetY, 'Frame')
            cvui.trackbar(frameCtrl, widgetX, widgetY + 10, widgetL, value, 0,
                          max_l - 1)
            cvui.counter(frameCtrl, widgetX, widgetY + 60, value)
            buttonclicked = cvui.button(
                frameCtrl, widgetX, widgetY + 90,
                "Ok, I want the tracking to end at this frame!")
            cvui.text(frameCtrl, widgetX, widgetY + 130,
                      'Keys: 4 or a: move backwards; 6 or d: move forward')
            cvui.text(frameCtrl, widgetX, widgetY + 160,
                      'Keys: g or f: fast backwards; h or j: fast forward')
            cvui.imshow(WINDOW_NAME, frame)
            cvui.imshow(WINDOW_NAME_CTRL, frameCtrl)
            r = cv2.waitKey(20)
            if (r == 54) or (r == 100) or (r == 0):
                value[0] = value[0] + 1
            elif (r == 52) or (r == 97) or (r == 113):
                value[0] = value[0] - 1
            elif (r == 103):
                value[0] = value[0] - 30
            elif (r == 104):
                value[0] = value[0] + 30
            elif (r == 102):
                value[0] = value[0] - 100
            elif (r == 106):
                value[0] = value[0] + 100
        self.configFile["lastFrame"] = int(value[0])
        cv2.destroyAllWindows()

    if int(self.configFile["headEmbeded"]) == 1:
        controller.show_frame("HeadEmbeded")
    else:
        if self.organism == 'zebrafishNew':
            controller.show_frame("NumberOfAnimals2")
        elif self.organism == 'zebrafish':
            controller.show_frame("NumberOfAnimals")
        else:
            controller.show_frame("NumberOfAnimalsCenterOfMass")
예제 #30
0
def findWells(videoPath, hyperparameters):

  if hyperparameters["noWellDetection"]:
    
    cap = cv2.VideoCapture(videoPath)
    if (cap.isOpened()== False): 
      print("Error opening video stream or file")
    frame_width  = int(cap.get(3))
    frame_height = int(cap.get(4))
    l = []
    well = { 'topLeftX' : 0 , 'topLeftY' : 0 , 'lengthX' : frame_width , 'lengthY': frame_height }
    l.append(well)
    return l
  
  # Multiple ROIs defined by user during the execution
  
  if int(hyperparameters["multipleROIsDefinedDuringExecution"]):
    l = []
    cap = cv2.VideoCapture(videoPath)
    if (cap.isOpened()== False): 
      print("Error opening video stream or file")
    ret, frame = cap.read()
    [frame, getRealValueCoefX, getRealValueCoefY, horizontal, vertical] = resizeImageTooLarge(frame, True, 0.85)
    cv2.waitKey(500)
    for i in range(0, int(hyperparameters["nbWells"])):
      WINDOW_NAME = "Click on the top left of one of the regions of interest"
      cvui.init(WINDOW_NAME)
      cv2.moveWindow(WINDOW_NAME, 0,0)
      cvui.imshow(WINDOW_NAME, frame)
      while not(cvui.mouse(cvui.CLICK)):
        cursor = cvui.mouse()
        cv2.waitKey(20)
      topLeft = [cursor.x, cursor.y]
      cv2.destroyWindow(WINDOW_NAME)
      WINDOW_NAME = "Click on the bottom right of the same region of interest"
      cvui.init(WINDOW_NAME)
      cv2.moveWindow(WINDOW_NAME, 0,0)
      cvui.imshow(WINDOW_NAME, frame)
      while not(cvui.mouse(cvui.CLICK)):
        cursor = cvui.mouse()
        cv2.waitKey(20)
      bottomRight = [cursor.x, cursor.y]
      frame = cv2.rectangle(frame, (topLeft[0], topLeft[1]), (bottomRight[0], bottomRight[1]), (255, 0, 0), 1)
      cv2.destroyWindow(WINDOW_NAME)
      frame_width  = int(getRealValueCoefX * (bottomRight[0] - topLeft[0]))
      frame_height = int(getRealValueCoefY * (bottomRight[1] - topLeft[1]))
      well = {'topLeftX' : int(getRealValueCoefX * topLeft[0]), 'topLeftY' : int(getRealValueCoefY * topLeft[1]), 'lengthX' : frame_width, 'lengthY': frame_height}
      l.append(well)
    cap.release()
    return l
  
  # One ROI definied in the configuration file
  
  if len(hyperparameters["oneWellManuallyChosenTopLeft"]):
    l = []
    topLeft_X = hyperparameters["oneWellManuallyChosenTopLeft"][0]
    topLeft_Y = hyperparameters["oneWellManuallyChosenTopLeft"][1]
    bottomRight_X = hyperparameters["oneWellManuallyChosenBottomRight"][0]
    bottomRight_Y = hyperparameters["oneWellManuallyChosenBottomRight"][1]
    frame_width  = bottomRight_X - topLeft_X
    frame_height = bottomRight_Y - topLeft_Y
    well = { 'topLeftX' : topLeft_X , 'topLeftY' : topLeft_Y , 'lengthX' : frame_width , 'lengthY': frame_height }
    l.append(well)
    return l
  
  # Circular or rectangular wells
  
  cap = cv2.VideoCapture(videoPath)
  if (cap.isOpened()== False): 
    print("Error opening video stream or file")
  ret, frame = cap.read()
  if hyperparameters["invertBlackWhiteOnImages"]:
    frame = 255 - frame
  
  if hyperparameters["wellsAreRectangles"]:
    if hyperparameters["adjustRectangularWellsDetect"]:
      rectangularWellsArea = findRectangularWellsArea(frame, videoPath, hyperparameters)
      initializeAdjustHyperparametersWindows("Rectangular Wells Detection: Adjust parameters until you get the right number of wells detected (on the right side)")
    else:
      rectangularWellsArea = hyperparameters["findRectangleWellArea"]
      
    wellPositions = findRectangularWells(frame, videoPath, hyperparameters, rectangularWellsArea)
  else:
    wellPositions = findCircularWells(frame, videoPath, hyperparameters)
  
  cap.release()
  
  # Sorting wells
  
  nbWellsPerRows = hyperparameters["nbWellsPerRows"]
  nbRowsOfWells  = hyperparameters["nbRowsOfWells"]
  
  if len(wellPositions) >= nbWellsPerRows * nbRowsOfWells:
    
    for i in range(0, len(wellPositions)):
      for j in range(0, len(wellPositions)-1):
        if wellPositions[j]['topLeftY'] > wellPositions[j+1]['topLeftY']:
          aux                = wellPositions[j]
          wellPositions[j]   = wellPositions[j+1]
          wellPositions[j+1] = aux
    
    if (nbRowsOfWells == 0):
      for i in range(0, len(wellPositions)):
        for j in range(0, len(wellPositions)-1):
          if wellPositions[j]['topLeftX'] > wellPositions[j+1]['topLeftX']:
            aux                = wellPositions[j]
            wellPositions[j]   = wellPositions[j+1]
            wellPositions[j+1] = aux
    else:
      for k in range(0, nbRowsOfWells):
        for i in range(nbWellsPerRows*k, nbWellsPerRows*(k+1)):
          for j in range(nbWellsPerRows*k, nbWellsPerRows*(k+1)-1):
            if wellPositions[j]['topLeftX'] > wellPositions[j+1]['topLeftX']:
              aux                = wellPositions[j]
              wellPositions[j]   = wellPositions[j+1]
              wellPositions[j+1] = aux   
  
  else:
    
    print("Not enough wells detected, please adjust your configuration file")
  
  # Creating validation image
  
  rectangleTickness = 2
  lengthY = len(frame)
  lengthX = len(frame[0])
  if len(wellPositions):
    perm1 = np.random.permutation(len(wellPositions)) * int(255/len(wellPositions))
    perm2 = np.random.permutation(len(wellPositions)) * int(255/len(wellPositions))
    perm3 = np.random.permutation(len(wellPositions)) * int(255/len(wellPositions))
    for i in range(0, len(wellPositions)):
      if hyperparameters["wellsAreRectangles"]:
        topLeft     = (wellPositions[i]['topLeftX'], wellPositions[i]['topLeftY'])
        bottomRight = (wellPositions[i]['topLeftX'] + wellPositions[i]['lengthX'], wellPositions[i]['topLeftY'] + wellPositions[i]['lengthY'])
        color = (int(perm1[i]), int(perm2[i]), int(perm3[i]))
        frame = cv2.rectangle(frame, topLeft, bottomRight, color, rectangleTickness)
      else:
        cv2.circle(frame, (int(wellPositions[i]['topLeftX'] + wellPositions[i]['lengthX'] / 2), int(wellPositions[i]['topLeftY'] + wellPositions[i]['lengthY'] / 2)), 170, (0,0,255), 2)
      cv2.putText(frame, str(i), (int(wellPositions[i]['topLeftX'] + wellPositions[i]['lengthX'] / 2), int(wellPositions[i]['topLeftY'] + wellPositions[i]['lengthY'] / 2)), cv2.FONT_HERSHEY_SIMPLEX, 4,(255,255,255),2,cv2.LINE_AA)
  frame = cv2.resize(frame, (int(lengthX/2), int(lengthY/2))) # ???
  cv2.imwrite(os.path.join(os.path.join(hyperparameters["outputFolder"], hyperparameters["videoName"]), "repartition.jpg"), frame )
  if hyperparameters["debugFindWells"]:
  
    frame2 = frame.copy()
    [frame2, getRealValueCoefX, getRealValueCoefY, horizontal, vertical] = resizeImageTooLarge(frame2)
  
    cv2.imshow('Wells Detection', frame2)
    if hyperparameters["exitAfterBackgroundExtraction"]:
      cv2.waitKey(3000)
    else:
      cv2.waitKey(0)
    cv2.destroyWindow('Wells Detection')
  
  print("Wells found")
  if hyperparameters["popUpAlgoFollow"]:
    popUpAlgoFollow.prepend("Wells found")

  return wellPositions