示例#1
0
def main():
	frame = np.zeros((150, 650, 3), np.uint8)

	# Init cvui and tell it to use a value of 20 for cv2.waitKey()
	# because we want to enable keyboard shortcut for
	# all components, e.g. button with label "&Quit".
	# If cvui has a value for waitKey, it will call
	# waitKey() automatically for us within cvui.update().
	cvui.init(WINDOW_NAME, 20);

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

		cvui.text(frame, 40, 40, 'To exit this app click the button below or press Q (shortcut for the button below).')

		# Exit the application if the quit button was pressed.
		# It can be pressed because of a mouse click or because 
		# the user pressed the "q" key on the keyboard, which is
		# marked as a shortcut in the button label ("&Quit").
		if cvui.button(frame, 300, 80, "&Quit"):
			break

		# Since cvui.init() received a param regarding waitKey,
		# there is no need to call cv.waitKey() anymore. cvui.update()
		# will do it automatically.
		cvui.update()
		
		cv2.imshow(WINDOW_NAME, frame)
示例#2
0
def main():
	frame = np.zeros((300, 600, 3), np.uint8)
	out = cv2.imread('lena-face.jpg', cv2.IMREAD_COLOR)
	down = cv2.imread('lena-face-red.jpg', cv2.IMREAD_COLOR)
	over = cv2.imread('lena-face-gray.jpg', cv2.IMREAD_COLOR)

	# 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)

		# Render an image-based button. You can provide images
		# to be used to render the button when the mouse cursor is
		# outside, over or down the button area.
		if cvui.button(frame, 200, 80, out, over, down):
			print('Image button clicked!')

		cvui.text(frame, 150, 200, 'This image behaves as a button')

		# Render a regular button.
		if cvui.button(frame, 360, 80, 'Button'):
			print('Regular button clicked!')

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
示例#3
0
def main():
	frame = np.zeros((300, 800, 3), np.uint8)
	value = [2.25]
	values = []

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

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

		# In a row, all added elements are
		# horizontally placed, one next the other (from left to right)
		#
		# Within the cvui.beginRow() and cvui.endRow(),
		# all elements will be automatically positioned by cvui.
		#
		# Notice that all component calls within the begin/end block
		# DO NOT have (x,y) coordinates.
		#
		# Let's create a row at position (20,80) with automatic width and height, and a padding of 10
		cvui.beginRow(frame, 20, 80, -1, -1, 10);
		
		# trackbar accepts a pointer to a variable that controls their value.
		# Here we define a double trackbar between 0. and 5.
		if cvui.trackbar(150, value, 0., 5.):
			print('Trackbar was modified, value : ', value[0])
			values.append(value[0])

		if len(values) > 5:
			cvui.text('Your edits on a sparkline ->')
			cvui.sparkline(values, 240, 60)

			if cvui.button('Clear sparkline'):
				values = []
		else:
			cvui.text('<- Move the trackbar')
		
		cvui.endRow();

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
示例#4
0
def main():
	fruits = cv2.imread('fruits.jpg', cv2.IMREAD_COLOR)
	frame = np.zeros(fruits.shape, np.uint8)
	low_threshold = [50]
	high_threshold = [150]
	use_canny = [False]

	# Create a settings window using the EnhancedWindow class.
	settings = EnhancedWindow(10, 50, 270, 180, 'Settings')

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

	while (True):
		# Should we apply Canny edge?
		if use_canny[0]:
			# Yes, we should apply it.
			frame = cv2.cvtColor(fruits, cv2.COLOR_BGR2GRAY)
			frame = cv2.Canny(frame, low_threshold[0], high_threshold[0], 3)
			frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
		else: 
			# No, so just copy the original image to the displaying frame.
			frame[:] = fruits[:]

		# Render the settings window and its content, if it is not minimized.
		settings.begin(frame)
		if settings.isMinimized() == False:
			cvui.checkbox('Use Canny Edge', use_canny)
			cvui.trackbar(settings.width() - 20, low_threshold, 5, 150)
			cvui.trackbar(settings.width() - 20, high_threshold, 80, 300)
			cvui.space(20); # add 20px of empty space
			cvui.text('Drag and minimize this settings window', 0.4, 0xff0000)
		settings.end()

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
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
def group(frame, x, y, width, height):
    padding = 5
    w = (width - padding) / 4
    h = (height - 15 - padding) / 2
    pos = cvui.Point(x + padding, y + 5)

    cvui.text(frame, pos.x, pos.y, 'Group title')
    pos.y += 15

    cvui.window(frame, pos.x, pos.y, width - padding * 2, h - padding,
                'Something')
    cvui.rect(frame, pos.x + 2, pos.y + 20, width - padding * 2 - 5,
              h - padding - 20, 0xff0000)
    pos.y += h

    cvui.window(frame, pos.x, pos.y, w / 3 - padding, h, 'Some')
    cvui.text(frame, pos.x + 25, pos.y + 60, '65', 1.1)
    pos.x += w / 3

    cvui.window(frame, pos.x, pos.y, w / 3 - padding, h, 'Info')
    cvui.text(frame, pos.x + 25, pos.y + 60, '30', 1.1)
    pos.x += w / 3

    cvui.window(frame, pos.x, pos.y, w / 3 - padding, h, 'Here')
    cvui.text(frame, pos.x + 25, pos.y + 60, '70', 1.1)
    pos.x += w / 3

    cvui.window(frame, pos.x, pos.y, w - padding, h, 'And')
    cvui.rect(frame, pos.x + 2, pos.y + 22, w - padding - 5, h - padding - 20,
              0xff0000)
    pos.x += w

    cvui.window(frame, pos.x, pos.y, w - padding, h, 'Here')
    cvui.rect(frame, pos.x + 2, pos.y + 22, w - padding - 5, h - padding - 20,
              0xff0000)
    pos.x += w

    cvui.window(frame, pos.x, pos.y, w - padding, h, 'More info')
    cvui.rect(frame, pos.x + 2, pos.y + 22, w - padding - 5, h - padding - 20,
              0xff0000)
    pos.x += w
示例#7
0
def group(frame, x, y, width, height):
	padding = 5
	w = (width - padding) / 4
	h = (height - 15 - padding) / 2
	pos = cvui.Point(x + padding, y + 5)

	cvui.text(frame, pos.x, pos.y, 'Group title')
	pos.y += 15

	cvui.window(frame, pos.x, pos.y, width - padding * 2, h - padding, 'Something')
	cvui.rect(frame, pos.x + 2, pos.y + 20, width - padding * 2 - 5, h - padding - 20, 0xff0000)
	pos.y += h

	cvui.window(frame, pos.x, pos.y, w / 3 - padding, h, 'Some')
	cvui.text(frame, pos.x + 25, pos.y + 60, '65', 1.1)
	pos.x += w / 3

	cvui.window(frame, pos.x, pos.y, w / 3 - padding, h, 'Info')
	cvui.text(frame, pos.x + 25, pos.y + 60, '30', 1.1)
	pos.x += w / 3

	cvui.window(frame, pos.x, pos.y, w / 3 - padding, h, 'Here')
	cvui.text(frame, pos.x + 25, pos.y + 60, '70', 1.1)
	pos.x += w / 3

	cvui.window(frame, pos.x, pos.y, w - padding, h, 'And')
	cvui.rect(frame, pos.x + 2, pos.y + 22, w - padding - 5, h - padding - 20, 0xff0000)
	pos.x += w

	cvui.window(frame, pos.x, pos.y, w - padding, h, 'Here')
	cvui.rect(frame, pos.x + 2, pos.y + 22, w - padding - 5, h - padding - 20, 0xff0000)
	pos.x += w

	cvui.window(frame, pos.x, pos.y, w - padding, h, 'More info')
	cvui.rect(frame, pos.x + 2, pos.y + 22, w - padding - 5, h - padding - 20, 0xff0000)
	pos.x += w
示例#8
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)
示例#9
0
def drawGUI(width, x):
    global actionValue
    global moveValue

    frame[:] = (49, 52, 49)
    cvui.rect(frame, 2, 2, 355, 120, 0xffaa77, 0x4444aa)
    cvui.rect(frame, 2, 125, 355, 55, 0xffaa77, 0x4444aa)

    #########################################################

    cvui.text(frame, x, 5, 'repeatValue (0 - 10)')
    cvui.trackbar(frame, x, 10, width, repeatValue, 0, 10, 1, '%.0Lf')

    cvui.text(frame, x, 65, 'moveValue (10 - 100)')
    cvui.trackbar(frame, x, 75, width, moveValue, 1, 100, 1, '%.0Lf')

    #########################################################

    cvui.text(frame, x + (80 * 1.25), 130, "role")

    if cvui.button(frame, x, 145, "Horizon"):
        return "Horizon"

    if cvui.button(frame, x + (80 * 1.25), 145, "Vertical"):
        return "Vertical"

    if cvui.button(frame, x + (80 * 2.5), 145, "Stop"):
        return "Stop"

    if cvui.button(frame, x + (80 * 3.5), 145, "Exit"):
        exit()

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

    return ""
示例#10
0
def page2(date,pcount,mimg,simg,stat):
    ok = cv2.imread('masterdata/ok.png')
    notok = cv2.imread('masterdata/notok.png')
    tpic=cv2.imread(mimg)
    ok = imutils.resize(ok, height=int(height*0.03))
    notok = imutils.resize(notok, height=int(height*0.03))
    [oy,ox,oa] = ok.shape
    tpic=imutils.resize(tpic, height=int(height*.84))
    [ty,tx,aa]=tpic.shape
    frame1[int(0.075*height):int(0.075*height)+ty, int(.01*width):int(.01*width)+tx]=tpic
    ipic=cv2.imread(simg)
    ipic=imutils.resize(ipic, height=int(height*.3))
    [iy,ix,aa]=ipic.shape
    frame1[int(0.15*height):int(0.15*height)+iy, int(.73*width):int(.73*width)+ix]=ipic
    bpic=cv2.imread("masterdata/datebg.png")
    bpic=imutils.resize(bpic, width=int(width*.28))
    [by,bx,ba]=bpic.shape
    frame1[int(0.71*height):int(0.71*height)+by, int(.72*width):int(.72*width)+bx]=bpic
    #print(oy,ox,oa)
    i=0.45
    for status in stat:
        i=i+0.05
        #print(i)
        if status==True:
            frame1[int(i*height):int(i*height)+oy, int(.9*width):int(.9*width)+ox]=ok
        elif status==False:
            frame1[int(i*height):int(i*height)+oy, int(.9*width):int(.9*width)+ox]=notok            
    cvui.text(frame1, int(0.75*width), int(.5*height), "Large Fuse",(0.001*height), 0x000000)
    cvui.text(frame1, int(0.75*width), int(.55*height),"Outer sealing" ,(0.001*height), 0x000000)
    cvui.text(frame1, int(0.75*width), int(.6*height), "Small Fuse",(0.001*height), 0x000000)
    cvui.text(frame1, int(0.75*width), int(.65*height), "Heatshrink",(0.001*height), 0x000000)
    cvui.text(frame1, int(0.72*width), int(.75*height), date,(0.001*height), 0x000000)
    cvui.text(frame1, int(0.72*width), int(.81*height), pcount,(0.001*height), 0x000000)
示例#11
0
文件: trackbar.py 项目: Dovyski/cvui
def main():
	intValue = [30]
	ucharValue = [30]
	charValue = [30]
	floatValue = [12.]
	doubleValue = [45.]
	doubleValue2 = [15.]
	doubleValue3 = [10.3]
	frame = np.zeros((770, 350, 3), np.uint8)

	# The width of all trackbars used in this example.
	width = 300

	# The x position of all trackbars used in this example
	x = 10

	# 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)

		# The trackbar component uses templates to guess the type of its arguments.
		# You have to be very explicit about the type of the value, the min and
		# the max params. For instance, if they are double, use 100.0 instead of 100.
		cvui.text(frame, x, 10, 'double, step 1.0 (default)')
		cvui.trackbar(frame, x, 40, width, doubleValue, 0., 100.)

		cvui.text(frame, x, 120, 'float, step 1.0 (default)')
		cvui.trackbar(frame, x, 150, width, floatValue, 10., 15.)

		# You can specify segments and custom labels. Segments are visual marks in
		# the trackbar scale. Internally the value for the trackbar is stored as
		# long double, so the custom labels must always format long double numbers, no
		# matter the type of the numbers being used for the trackbar. E.g. %.2Lf
		cvui.text(frame, x, 230, 'double, 4 segments, custom label %.2Lf')
		cvui.trackbar(frame, x, 260, width, doubleValue2, 0., 20., 4, '%.2Lf')

		# Again: you have to be very explicit about the value, the min and the max params.
		# Below is a uchar trackbar. Observe the uchar cast for the min, the max and 
		# the step parameters.
		cvui.text(frame, x, 340, 'uchar, custom label %.0Lf')
		cvui.trackbar(frame, x, 370, width, ucharValue, 0, 255, 0, '%.0Lf')

		# You can change the behavior of any tracker by using the options parameter.
		# Options are defined as a bitfield, so you can combine them.
		# E.g.
		#	TRACKBAR_DISCRETE							# value changes are discrete
		#  TRACKBAR_DISCRETE | TRACKBAR_HIDE_LABELS	# discrete changes and no labels
		cvui.text(frame, x, 450, 'double, step 0.1, option TRACKBAR_DISCRETE')
		cvui.trackbar(frame, x, 480, width, doubleValue3, 10., 10.5, 1, '%.1Lf', cvui.TRACKBAR_DISCRETE, 0.1)

		# More customizations using options.
		options = cvui.TRACKBAR_DISCRETE | cvui.TRACKBAR_HIDE_SEGMENT_LABELS
		cvui.text(frame, x, 560, 'int, 3 segments, DISCRETE | HIDE_SEGMENT_LABELS')
		cvui.trackbar(frame, x, 590, width, intValue, 10, 50, 3, '%.0Lf', options, 2)

		# Trackbar using char type.
		cvui.text(frame, x, 670, 'char, 2 segments, custom label %.0Lf')
		cvui.trackbar(frame, x, 700, width, charValue, -128, 127, 2, '%.0Lf')

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
示例#12
0
                   anchorTV=anchorTV[0],
                   scanIntervals=scanIntervals[0],
                   Mean=mean[0],
                   times=times[0],
                   alpha=alpha[0],
                   ksize=ksize[0]))[1].tofile(name + "lowpoly.jpg")


startFlag = False
global thds
thds = 7
global Size
while True:
    # your app logic here
    frame[:] = (49, 52, 49)
    cvui.text(frame, 50, 750, 'Produced by BQSG', .6)
    cvui.beginColumn(frame, 10, 20)
    if (cvui.button("&OpenFile")):
        file_path = filedialog.askopenfilename()
        # print(file_path)
        if isVideo[0]:
            try:
                cap = cv2.VideoCapture(file_path)
                sumcnt = int(round(cap.get(cv2.CAP_PROP_FRAME_COUNT)))
                print(sumcnt)
                for i in range(sumcnt):
                    ret, image = cap.read()
                    if ret:
                        if image.shape[0] > image.shape[1]:
                            image = cv2.resize(image, (int(
                                800 * image.shape[1] / image.shape[0]), 800),
示例#13
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]
示例#14
0
def main():
    intValue = [30]
    ucharValue = [30]
    charValue = [30]
    floatValue = [12.]
    doubleValue = [45.]
    doubleValue2 = [15.]
    doubleValue3 = [10.3]
    frame = np.zeros((770, 350, 3), np.uint8)

    # The width of all trackbars used in this example.
    width = 300

    # The x position of all trackbars used in this example
    x = 10

    # 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)

        # The trackbar component uses templates to guess the type of its arguments.
        # You have to be very explicit about the type of the value, the min and
        # the max params. For instance, if they are double, use 100.0 instead of 100.
        cvui.text(frame, x, 10, 'double, step 1.0 (default)')
        cvui.trackbar(frame, x, 40, width, doubleValue, 0., 100.)

        cvui.text(frame, x, 120, 'float, step 1.0 (default)')
        cvui.trackbar(frame, x, 150, width, floatValue, 10., 15.)

        # You can specify segments and custom labels. Segments are visual marks in
        # the trackbar scale. Internally the value for the trackbar is stored as
        # long double, so the custom labels must always format long double numbers, no
        # matter the type of the numbers being used for the trackbar. E.g. %.2Lf
        cvui.text(frame, x, 230, 'double, 4 segments, custom label %.2Lf')
        cvui.trackbar(frame, x, 260, width, doubleValue2, 0., 20., 4, '%.2Lf')

        # Again: you have to be very explicit about the value, the min and the max params.
        # Below is a uchar trackbar. Observe the uchar cast for the min, the max and
        # the step parameters.
        cvui.text(frame, x, 340, 'uchar, custom label %.0Lf')
        cvui.trackbar(frame, x, 370, width, ucharValue, 0, 255, 0, '%.0Lf')

        # You can change the behavior of any tracker by using the options parameter.
        # Options are defined as a bitfield, so you can combine them.
        # E.g.
        #	TRACKBAR_DISCRETE							# value changes are discrete
        #  TRACKBAR_DISCRETE | TRACKBAR_HIDE_LABELS	# discrete changes and no labels
        cvui.text(frame, x, 450, 'double, step 0.1, option TRACKBAR_DISCRETE')
        cvui.trackbar(frame, x, 480, width, doubleValue3, 10., 10.5, 1,
                      '%.1Lf', cvui.TRACKBAR_DISCRETE, 0.1)

        # More customizations using options.
        options = cvui.TRACKBAR_DISCRETE | cvui.TRACKBAR_HIDE_SEGMENT_LABELS
        cvui.text(frame, x, 560,
                  'int, 3 segments, DISCRETE | HIDE_SEGMENT_LABELS')
        cvui.trackbar(frame, x, 590, width, intValue, 10, 50, 3, '%.0Lf',
                      options, 2)

        # Trackbar using char type.
        cvui.text(frame, x, 670, 'char, 2 segments, custom label %.0Lf')
        cvui.trackbar(frame, x, 700, width, charValue, -128, 127, 2, '%.0Lf')

        # This function must be called *AFTER* all UI components. It does
        # all the behind the scenes magic to handle mouse clicks, etc.
        cvui.update()

        # Show everything on the screen
        cv2.imshow(WINDOW_NAME, frame)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
示例#15
0
    displ = left_matcher.compute(grayLeft, grayRight)  #.astype(np.float32)/16
    displ = np.int16(displ)

    filteredImg = cv2.normalize(src=displ,
                                dst=None,
                                beta=0,
                                alpha=255,
                                norm_type=cv2.NORM_MINMAX,
                                dtype=cv2.CV_8UC1)
    filteredImg = cv2.applyColorMap(filteredImg, cv2.COLORMAP_BONE)

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

    cvui.text(frame, 50, 20, 'Block Size: ')
    cvui.trackbar(frame, 25, 40, 600, blockSize, 5, 101, 2, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 2)

    cvui.text(frame, 50, 120, 'numDisparites')
    cvui.trackbar(frame, 25, 140, 600, numDisparities, 16, 198, 16, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 16)

    cvui.text(frame, 50, 220, 'Uniqueness Ratio: ')
    cvui.trackbar(frame, 25, 240, 600, uniquessRatio, 0, 100, 1, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 1)

    cvui.text(frame, 50, 320, 'speckleRange: ')
    cvui.trackbar(frame, 25, 340, 600, speckleRange, 0, 100, 1, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 1)
示例#16
0
def main():
    # We have one mat for each window.
    frame1 = np.zeros((600, 800, 3), np.uint8)
    frame2 = np.zeros((600, 800, 3), np.uint8)

    # Create variables used by some components
    window1_values = []
    window2_values = []
    window1_checked = [False]
    window1_checked2 = [False]
    window2_checked = [False]
    window2_checked2 = [False]
    window1_value = [1.0]
    window1_value2 = [1.0]
    window1_value3 = [1.0]
    window2_value = [1.0]
    window2_value2 = [1.0]
    window2_value3 = [1.0]

    img = cv2.imread('lena-face.jpg', cv2.IMREAD_COLOR)
    imgRed = cv2.imread('lena-face-red.jpg', cv2.IMREAD_COLOR)
    imgGray = cv2.imread('lena-face-gray.jpg', cv2.IMREAD_COLOR)

    padding = 10

    # Fill the vector with a few random values
    for i in range(0, 20):
        window1_values.append(random.uniform(0., 300.0))
        window2_values.append(random.uniform(0., 300.0))

    # Start two OpenCV windows
    cv2.namedWindow(WINDOW1_NAME)
    cv2.namedWindow(WINDOW2_NAME)

    # Init cvui and inform it to use the first window as the default one.
    # cvui.init() will automatically watch the informed window.
    cvui.init(WINDOW1_NAME)

    # Tell cvui to keep track of mouse events in window2 as well.
    cvui.watch(WINDOW2_NAME)

    while (True):
        # Inform cvui that all subsequent component calls and events are related to window 1.
        cvui.context(WINDOW1_NAME)

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

        cvui.beginRow(frame1, 10, 20, 100, 50)
        cvui.text('This is ')
        cvui.printf('a row')
        cvui.checkbox('checkbox', window1_checked)
        cvui.window(80, 80, 'window')
        cvui.rect(50, 50, 0x00ff00, 0xff0000)
        cvui.sparkline(window1_values, 50, 50)
        cvui.counter(window1_value)
        cvui.button(100, 30, 'Fixed')
        cvui.image(img)
        cvui.button(img, imgGray, imgRed)
        cvui.endRow()

        padding = 50
        cvui.beginRow(frame1, 10, 150, 100, 50, padding)
        cvui.text('This is ')
        cvui.printf('another row')
        cvui.checkbox('checkbox', window1_checked2)
        cvui.window(80, 80, 'window')
        cvui.button(100, 30, 'Fixed')
        cvui.printf('with 50px paddin7hg.')
        cvui.endRow()

        cvui.beginRow(frame1, 10, 250, 100, 50)
        cvui.text('This is ')
        cvui.printf('another row with a trackbar ')
        cvui.trackbar(150, window1_value2, 0., 5.)
        cvui.printf(' and a button ')
        cvui.button(100, 30, 'button')
        cvui.endRow()

        cvui.beginColumn(frame1, 50, 330, 100, 200)
        cvui.text('Column 1 (no padding)')
        cvui.button('button1')
        cvui.button('button2')
        cvui.text('End of column 1')
        cvui.endColumn()

        padding = 10
        cvui.beginColumn(frame1, 300, 330, 100, 200, padding)
        cvui.text('Column 2 (padding = 10)')
        cvui.button('button1')
        cvui.button('button2')
        cvui.trackbar(150, window1_value3, 0., 5., 1, '%3.2Lf',
                      cvui.TRACKBAR_DISCRETE, 0.25)
        cvui.text('End of column 2')
        cvui.endColumn()

        cvui.beginColumn(frame1, 550, 330, 100, 200)
        cvui.text('Column 3 (use space)')
        cvui.space(5)
        cvui.button('button1 5px below')
        cvui.space(50)
        cvui.text('Text 50px below')
        cvui.space(20)
        cvui.button('Button 20px below')
        cvui.space(40)
        cvui.text('End of column 2 (40px below)')
        cvui.endColumn()

        # Update all components of window1, e.g. mouse clicks, and show it.
        cvui.update(WINDOW1_NAME)
        cv2.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.
        # We do that by calling cvui.context().
        cvui.context(WINDOW2_NAME)
        frame2[:] = (49, 52, 49)

        cvui.beginRow(frame2, 10, 20, 100, 50)
        cvui.text('This is ')
        cvui.printf('a row')
        cvui.checkbox('checkbox', window2_checked)
        cvui.window(80, 80, 'window')
        cvui.rect(50, 50, 0x00ff00, 0xff0000)
        cvui.sparkline(window2_values, 50, 50)
        cvui.counter(window2_value)
        cvui.button(100, 30, 'Fixed')
        cvui.image(img)
        cvui.button(img, imgGray, imgRed)
        cvui.endRow()

        padding = 50
        cvui.beginRow(frame2, 10, 150, 100, 50, padding)
        cvui.text('This is ')
        cvui.printf('another row')
        cvui.checkbox('checkbox', window2_checked2)
        cvui.window(80, 80, 'window')
        cvui.button(100, 30, 'Fixed')
        cvui.printf('with 50px paddin7hg.')
        cvui.endRow()

        # Another row mixing several components
        cvui.beginRow(frame2, 10, 250, 100, 50)
        cvui.text('This is ')
        cvui.printf('another row with a trackbar ')
        cvui.trackbar(150, window2_value2, 0., 5.)
        cvui.printf(' and a button ')
        cvui.button(100, 30, 'button')
        cvui.endRow()

        cvui.beginColumn(frame2, 50, 330, 100, 200)
        cvui.text('Column 1 (no padding)')
        cvui.button('button1')
        cvui.button('button2')
        cvui.text('End of column 1')
        cvui.endColumn()

        padding = 10
        cvui.beginColumn(frame2, 300, 330, 100, 200, padding)
        cvui.text('Column 2 (padding = 10)')
        cvui.button('button1')
        cvui.button('button2')
        cvui.trackbar(150, window2_value3, 0., 5., 1, '%3.2Lf',
                      cvui.TRACKBAR_DISCRETE, 0.25)
        cvui.text('End of column 2')
        cvui.endColumn()

        cvui.beginColumn(frame2, 550, 330, 100, 200)
        cvui.text('Column 3 (use space)')
        cvui.space(5)
        cvui.button('button1 5px below')
        cvui.space(50)
        cvui.text('Text 50px below')
        cvui.space(20)
        cvui.button('Button 20px below')
        cvui.space(40)
        cvui.text('End of column 2 (40px below)')
        cvui.endColumn()

        # Update all components of window2, e.g. mouse clicks, and show it.
        cvui.update(WINDOW2_NAME)
        cv2.imshow(WINDOW2_NAME, frame2)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
            printScreen = cv2.resize(printScreen, None, fx=0.7, fy=0.7)
            printScreen = cv2.cvtColor(printScreen, cv2.COLOR_RGB2BGR)
            printScreen = cv2.cvtColor(printScreen, cv2.COLOR_BGR2RGB)
            cvui.image(frame, 20, 20, printScreen)

        if cvui.button(frame, 400, 400, "Select window"):
            if run_button == 0:
                run_button = 1

            if run_button == 1:
                run_button = 0
                titlee = program_list[0]

        if run_button2 == 0:
            cvui.text(frame, 10, 305, "Capture Area")
            cvui.text(frame, 10, 355, "Min Max")

            cvui.text(frame, 100, 285, "Starting")
            cvui.counter(frame, 100, 300, Starting, 10)
            cvui.text(frame, 200, 285, "Width")
            cvui.counter(frame, 200, 300, area_width, 10)
            cvui.text(frame, 300, 285, "Height")
            cvui.counter(frame, 300, 300, area_height, 10)
            cvui.text(frame, 100, 335, "Max")
            cvui.counter(frame, 100, 350, cap_max, 100)
            cvui.text(frame, 200, 335, "Min")
            cvui.counter(frame, 200, 350, cap_min, 100)
            cvui.text(frame, 300, 335, "sensitivity")
            cvui.counter(frame, 300, 350, sensitivity, 1)
            cvui.window(frame, 30, 390, 360, 100, "Log")
示例#18
0
def fizeau(frame, expr):
    curr_expr = expr
    experiments = [[False] for i in range(2)]

    fizeau_default = cv2.imread(resource_path("images/fizeau_default.png"), 3)
    fizeau_not_default = cv2.imread(resource_path("images/fizeau_not_default.png"), 3)
    fizeau_line = cv2.imread(resource_path("images/fizeau_line.png"), 3)
    fizeau_distance = cv2.imread(resource_path("images/fizeau_distance.png"), 3)
    fizeau_dot = cv2.imread(resource_path("images/fizeau_dot.png"), cv2.IMREAD_UNCHANGED)
    fizeau_dot_grey = cv2.imread(resource_path("images/fizeau_dot_grey.png"), cv2.IMREAD_UNCHANGED)
    fizeau_sprocket = cv2.imread(resource_path("images/fizeau_sprocket.png"), cv2.IMREAD_UNCHANGED)
    fizeau_metre = cv2.imread(resource_path("images/fizeau_metre.png"), cv2.IMREAD_UNCHANGED)
    fizeau_blank = cv2.imread(resource_path("images/fizeau_blank.png"), cv2.IMREAD_UNCHANGED)
    fizeau_darkstripes = cv2.imread(resource_path("images/fizeau_darkstripes.png"), cv2.IMREAD_UNCHANGED)
    fizeau_lightstripes = cv2.imread(resource_path("images/fizeau_lightstripes.png"), cv2.IMREAD_UNCHANGED)

    wheel_sprites_pos = get_120(fizeau_default, fizeau_sprocket)
    wheel_sprites_pos = put_dots_pos(wheel_sprites_pos, fizeau_dot, fizeau_dot_grey)
    wheel_sprites_pos.rotate(30)
    wheel_sprites_pos = put_dots_pos(wheel_sprites_pos, fizeau_dot, fizeau_dot_grey)
    wheel_sprites_pos.rotate(30)
    wheel_sprites_pos = put_dots_pos(wheel_sprites_pos, fizeau_dot, fizeau_dot_grey)
    wheel_sprites_pos.rotate(30)
    wheel_sprites_pos = put_dots_pos(wheel_sprites_pos, fizeau_dot, fizeau_dot_grey)

    wheel_sprites_neg = get_120(fizeau_not_default, fizeau_sprocket)
    wheel_sprites_neg = put_dots_neg(wheel_sprites_neg, fizeau_dot, fizeau_dot_grey)
    wheel_sprites_neg.rotate(30)
    wheel_sprites_neg = put_dots_neg(wheel_sprites_neg, fizeau_dot, fizeau_dot_grey)
    wheel_sprites_neg.rotate(30)
    wheel_sprites_neg = put_dots_neg(wheel_sprites_neg, fizeau_dot, fizeau_dot_grey)
    wheel_sprites_neg.rotate(30)
    wheel_sprites_neg = put_dots_neg(wheel_sprites_neg, fizeau_dot, fizeau_dot_grey)

    animation = 0
    frequency_tr = [6.0]

    while (True):
        frame[:] = (49,52,49)

        #Animation window
        coord = get_coord(frequency_tr[0])
        if coord == 23:
            cvui.image(frame, 0, 0, wheel_sprites_neg[animation])
            cvui.text(frame, 33, 200, "Calculation of the speed of light", 0.5)
            cvui.text(frame, 34, 220, "distance ... s = {:,} m" .format(8633), 0.5)
            cvui.text(frame, 34, 240, "number of teeth in sprocket ... N = 720", 0.5)
            cvui.text(frame, 34, 260, "c=4*s*N*f=4*{:,}*{:,}*{:,}={:,} km/s"
                .format(8633, 7200, round(frequency_tr[0], 2), round((4 * 8633 * 7200 * frequency_tr[0])/1000, 2)), 0.5)
        else:
            cvui.image(frame, 0, 0, wheel_sprites_pos[animation])
            cvui.text(frame, 33, 200, "Calculation of the speed of light", 0.5)
            cvui.text(frame, 34, 220, "distance ... s = {:,} m" .format(8633), 0.5)
            cvui.text(frame, 34, 240, "number of teeth in sprocket ... N = 720", 0.5)
            cvui.text(frame, 34, 260, "c=4*s*N*f ... proper frequency wasn't found", 0.5)
        cvui.image(frame, 872, 499, fizeau_line)

        cvui.image(frame, 874, 687, fizeau_distance)
        animation += 1
        if animation == 120:
            animation = 0

        cvui.text(frame,   58, 660, "Light source")
        cvui.text(frame,  473, 660, "Semipermeable mirror")
        cvui.text(frame,  840, 660, "Sprocket")
        cvui.text(frame,  994, 673, "Distance")
        cvui.text(frame, 1145, 660, "Mirror")

        cvui.text(frame, 892, 277, "-> Light behind sprocket")
        img = get_graph(fizeau_metre, fizeau_blank, fizeau_darkstripes, fizeau_lightstripes, coord=0, crop_light=False)
        cvui.image(frame, 896, 298, img)
        cvui.text(frame, 892, 377, "<- Reflected light before sprocket")
        img = get_graph(fizeau_metre, fizeau_blank, fizeau_darkstripes, fizeau_lightstripes, coord=coord, crop_light=False)
        cvui.image(frame, 896, 397, img)
        cvui.text(frame, 434, 100, "Reflected light behind sprocket")
        img = get_graph(fizeau_metre, fizeau_blank, fizeau_darkstripes, fizeau_lightstripes, coord=coord, crop_light=True)
        cvui.image(frame, 434, 120, img)

        #Experiment settings window
        cvui.window(frame, 1033.5, 2, 243.5, 104, 'Experiment settings')
        
        cvui.trackbar(frame,  1030, 39, 249, frequency_tr, 0.01, 12.0577)
        cvui.rect(frame, 1035, 39, 240, 12, 0x313131, 0x313131)
        cvui.rect(frame, 1035, 74, 240, 25, 0x313131, 0x313131)
        cvui.text(frame, 1041, 32, "Frequency")
        cvui.text(frame, 1042, 82, "{:,} Hz".format(round(frequency_tr[0], 2)))

        #Experiments window
        cvui.window(frame, 2, 2, 155, 75, 'Experiments')

        cvui.checkbox(frame, 10, 30, "1638 - Galileo",   experiments[0])
        cvui.checkbox(frame, 10, 53, "1849 - Fizeau",    experiments[1])

        curr_expr = exp_type(curr_expr, experiments)
        experiments = [[False] for i in range(2)]
        experiments[curr_expr] = [True]

        cvui.update()

        cv2.imshow('Speed of Light Measurement', frame)

        if cv2.waitKey(20) == 27:
            return -1

        if curr_expr != expr:
            return curr_expr
示例#19
0
def main():
    intValue = [30]
    ucharValue = [30]
    charValue = [30]
    floatValue = [12.]
    doubleValue1 = [15.]
    doubleValue2 = [10.3]
    doubleValue3 = [2.25]
    frame = np.zeros((650, 450, 3), np.uint8)

    # Size of trackbars
    width = 400

    # Init cvui and tell it to use a value of 20 for cv2.waitKey()
    # because we want to enable keyboard shortcut for
    # all components, e.g. button with label '&Quit'.
    # If cvui has a value for waitKey, it will call
    # waitKey() automatically for us within cvui.update().
    cvui.init(WINDOW_NAME, 20)

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

        cvui.beginColumn(frame, 20, 20, -1, -1, 6)

        cvui.text('int trackbar, no customization')
        cvui.trackbar(width, intValue, 0, 100)
        cvui.space(5)

        cvui.text('uchar trackbar, no customization')
        cvui.trackbar(width, ucharValue, 0, 255)
        cvui.space(5)

        cvui.text('signed char trackbar, no customization')
        cvui.trackbar(width, charValue, -128, 127)
        cvui.space(5)

        cvui.text('float trackbar, no customization')
        cvui.trackbar(width, floatValue, 10., 15.)
        cvui.space(5)

        cvui.text('float trackbar, 4 segments')
        cvui.trackbar(width, doubleValue1, 10., 20., 4)
        cvui.space(5)

        cvui.text('double trackbar, label %.1Lf, TRACKBAR_DISCRETE')
        cvui.trackbar(width, doubleValue2, 10., 10.5, 1, '%.1Lf',
                      cvui.TRACKBAR_DISCRETE, 0.1)
        cvui.space(5)

        cvui.text(
            'double trackbar, label %.2Lf, 2 segments, TRACKBAR_DISCRETE')
        cvui.trackbar(width, doubleValue3, 0., 4., 2, '%.2Lf',
                      cvui.TRACKBAR_DISCRETE, 0.25)
        cvui.space(10)

        # Exit the application if the quit button was pressed.
        # It can be pressed because of a mouse click or because
        # the user pressed the 'q' key on the keyboard, which is
        # marked as a shortcut in the button label ('&Quit').
        if cvui.button('&Quit'):
            break

        cvui.endColumn()

        # Since cvui.init() received a param regarding waitKey,
        # there is no need to call cv.waitKey() anymore. cvui.update()
        # will do it automatically.
        cvui.update()

        cv2.imshow(WINDOW_NAME, frame)
示例#20
0
def main():
    # We have one mat for each window.
    frame1 = np.zeros((150, 600, 3), np.uint8)
    frame2 = np.zeros((150, 600, 3), np.uint8)
    error_frame = np.zeros((100, 300, 3), np.uint8)

    # Flag to control if we should show an error window.
    error = False

    # Create two OpenCV windows
    cv2.namedWindow(GUI_WINDOW1_NAME)
    cv2.namedWindow(GUI_WINDOW2_NAME)

    # Init cvui and inform it to use the first window as the default one.
    # cvui.init() will automatically watch the informed window.
    cvui.init(GUI_WINDOW1_NAME)

    # Tell cvui to keep track of mouse events in window2 as well.
    cvui.watch(GUI_WINDOW2_NAME)

    while (True):
        # Inform cvui that all subsequent component calls and events are related to window 1.
        cvui.context(GUI_WINDOW1_NAME)

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

        cvui.beginColumn(frame1, 50, 20, -1, -1, 10)
        cvui.text('[Win1] Use the buttons below to control the error window')

        if cvui.button('Close'):
            closeWindow(ERROR_WINDOW_NAME)

        # If the button is clicked, we open the error window.
        # The content and rendering of such error window will be performed
        # after we handled all other windows.
        if cvui.button('Open'):
            error = True
            openWindow(ERROR_WINDOW_NAME)
        cvui.endColumn()

        # Update all components of window1, e.g. mouse clicks, and show it.
        cvui.update(GUI_WINDOW1_NAME)
        cv2.imshow(GUI_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.
        # We do that by calling cvui.context().
        cvui.context(GUI_WINDOW2_NAME)
        frame2[:] = (49, 52, 49)

        cvui.beginColumn(frame2, 50, 20, -1, -1, 10)
        cvui.text('[Win2] Use the buttons below to control the error window')

        if cvui.button('Close'):
            closeWindow(ERROR_WINDOW_NAME)

        # If the button is clicked, we open the error window.
        # The content and rendering of such error window will be performed
        # after we handled all other windows.
        if cvui.button('Open'):
            openWindow(ERROR_WINDOW_NAME)
            error = True
        cvui.endColumn()

        # Update all components of window2, e.g. mouse clicks, and show it.
        cvui.update(GUI_WINDOW2_NAME)
        cv2.imshow(GUI_WINDOW2_NAME, frame2)

        # Handle the content and rendering of the error window,
        # if we have un active error and the window is actually open.
        if error and isWindowOpen(ERROR_WINDOW_NAME):
            # Inform cvui that all subsequent component calls and events are
            # related to the error window from now on
            cvui.context(ERROR_WINDOW_NAME)

            # Fill the error window if a vibrant color
            error_frame[:] = (10, 10, 49)

            cvui.text(error_frame, 70, 20, 'This is an error message', 0.4,
                      0xff0000)

            if cvui.button(error_frame, 110, 40, 'Close'):
                error = False

            if error:
                # We still have an active error.
                # Update all components of the error window, e.g. mouse clicks, and show it.
                cvui.update(ERROR_WINDOW_NAME)
                cv2.imshow(ERROR_WINDOW_NAME, error_frame)
            else:
                # No more active error. Let's close the error window.
                closeWindow(ERROR_WINDOW_NAME)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
def main():
	# We have one mat for each window.
	frame1 = np.zeros((150, 600, 3), np.uint8)
	frame2 = np.zeros((150, 600, 3), np.uint8)
	error_frame = np.zeros((100, 300, 3), np.uint8)

	# Flag to control if we should show an error window.
	error = False

	# Create two OpenCV windows
	cv2.namedWindow(GUI_WINDOW1_NAME)
	cv2.namedWindow(GUI_WINDOW2_NAME)
	
	# Init cvui and inform it to use the first window as the default one.
	# cvui.init() will automatically watch the informed window.
	cvui.init(GUI_WINDOW1_NAME)

	# Tell cvui to keep track of mouse events in window2 as well.
	cvui.watch(GUI_WINDOW2_NAME)

	while (True):
		# Inform cvui that all subsequent component calls and events are related to window 1.
		cvui.context(GUI_WINDOW1_NAME)

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

		cvui.beginColumn(frame1, 50, 20, -1, -1, 10)
		cvui.text('[Win1] Use the buttons below to control the error window')
			
		if cvui.button('Close'):
			closeWindow(ERROR_WINDOW_NAME)

		# If the button is clicked, we open the error window.
		# The content and rendering of such error window will be performed
		# after we handled all other windows.
		if cvui.button('Open'):
			error = True
			openWindow(ERROR_WINDOW_NAME)
		cvui.endColumn()

		# Update all components of window1, e.g. mouse clicks, and show it.
		cvui.update(GUI_WINDOW1_NAME)
		cv2.imshow(GUI_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.
		# We do that by calling cvui.context().
		cvui.context(GUI_WINDOW2_NAME)
		frame2[:] = (49, 52, 49)
		
		cvui.beginColumn(frame2, 50, 20, -1, -1, 10)
		cvui.text('[Win2] Use the buttons below to control the error window')

		if cvui.button('Close'):
			closeWindow(ERROR_WINDOW_NAME)

		# If the button is clicked, we open the error window.
		# The content and rendering of such error window will be performed
		# after we handled all other windows.
		if cvui.button('Open'):
			openWindow(ERROR_WINDOW_NAME)
			error = True
		cvui.endColumn()

		# Update all components of window2, e.g. mouse clicks, and show it.
		cvui.update(GUI_WINDOW2_NAME)
		cv2.imshow(GUI_WINDOW2_NAME, frame2)

		# Handle the content and rendering of the error window,
		# if we have un active error and the window is actually open.
		if error and isWindowOpen(ERROR_WINDOW_NAME):
			# Inform cvui that all subsequent component calls and events are
			# related to the error window from now on
			cvui.context(ERROR_WINDOW_NAME)

			# Fill the error window if a vibrant color
			error_frame[:] = (10, 10, 49)

			cvui.text(error_frame, 70, 20, 'This is an error message', 0.4, 0xff0000)

			if cvui.button(error_frame, 110, 40, 'Close'):
				error = False

			if error:
				# We still have an active error.
				# Update all components of the error window, e.g. mouse clicks, and show it.
				cvui.update(ERROR_WINDOW_NAME)
				cv2.imshow(ERROR_WINDOW_NAME, error_frame)
			else:
				# No more active error. Let's close the error window.
				closeWindow(ERROR_WINDOW_NAME)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
示例#22
0
 def text(self, x, y, info, charsize=1, charcolor=0xff0000):
     cvui.text(self.background, y, x, info, charsize, charcolor)
示例#23
0
def main():
	# We have one mat for each window.
	frame1 = np.zeros((600, 800, 3), np.uint8)
	frame2 = np.zeros((600, 800, 3), np.uint8)

	# Create variables used by some components
	window1_values = []
	window2_values = []
	window1_checked = [False]
	window1_checked2 = [False]
	window2_checked = [False]
	window2_checked2 = [False]
	window1_value = [1.0]
	window1_value2 = [1.0]
	window1_value3 = [1.0]
	window2_value = [1.0]
	window2_value2 = [1.0]
	window2_value3 = [1.0]

	img = cv2.imread('lena-face.jpg', cv2.IMREAD_COLOR)
	imgRed = cv2.imread('lena-face-red.jpg', cv2.IMREAD_COLOR)
	imgGray = cv2.imread('lena-face-gray.jpg', cv2.IMREAD_COLOR)

	padding = 10

	# Fill the vector with a few random values
	for i in range(0, 20):
		window1_values.append(random.uniform(0., 300.0))
		window2_values.append(random.uniform(0., 300.0))

	# Start two OpenCV windows
	cv2.namedWindow(WINDOW1_NAME)
	cv2.namedWindow(WINDOW2_NAME)
	
	# Init cvui and inform it to use the first window as the default one.
	# cvui.init() will automatically watch the informed window.
	cvui.init(WINDOW1_NAME)

	# Tell cvui to keep track of mouse events in window2 as well.
	cvui.watch(WINDOW2_NAME)

	while (True):
		# Inform cvui that all subsequent component calls and events are related to window 1.
		cvui.context(WINDOW1_NAME)

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

		cvui.beginRow(frame1, 10, 20, 100, 50)
		cvui.text('This is ')
		cvui.printf('a row')
		cvui.checkbox('checkbox', window1_checked)
		cvui.window(80, 80, 'window')
		cvui.rect(50, 50, 0x00ff00, 0xff0000)
		cvui.sparkline(window1_values, 50, 50)
		cvui.counter(window1_value)
		cvui.button(100, 30, 'Fixed')
		cvui.image(img)
		cvui.button(img, imgGray, imgRed)
		cvui.endRow()

		padding = 50
		cvui.beginRow(frame1, 10, 150, 100, 50, padding)
		cvui.text('This is ')
		cvui.printf('another row')
		cvui.checkbox('checkbox', window1_checked2)
		cvui.window(80, 80, 'window')
		cvui.button(100, 30, 'Fixed')
		cvui.printf('with 50px paddin7hg.')
		cvui.endRow()

		cvui.beginRow(frame1, 10, 250, 100, 50)
		cvui.text('This is ')
		cvui.printf('another row with a trackbar ')
		cvui.trackbar(150, window1_value2, 0., 5.)
		cvui.printf(' and a button ')
		cvui.button(100, 30, 'button')
		cvui.endRow()

		cvui.beginColumn(frame1, 50, 330, 100, 200)
		cvui.text('Column 1 (no padding)')
		cvui.button('button1')
		cvui.button('button2')
		cvui.text('End of column 1')
		cvui.endColumn()

		padding = 10
		cvui.beginColumn(frame1, 300, 330, 100, 200, padding)
		cvui.text('Column 2 (padding = 10)')
		cvui.button('button1')
		cvui.button('button2')
		cvui.trackbar(150, window1_value3, 0., 5., 1, '%3.2Lf', cvui.TRACKBAR_DISCRETE, 0.25)
		cvui.text('End of column 2')
		cvui.endColumn()

		cvui.beginColumn(frame1, 550, 330, 100, 200)
		cvui.text('Column 3 (use space)')
		cvui.space(5)
		cvui.button('button1 5px below')
		cvui.space(50)
		cvui.text('Text 50px below')
		cvui.space(20)
		cvui.button('Button 20px below')
		cvui.space(40)
		cvui.text('End of column 2 (40px below)')
		cvui.endColumn()
		
		# Update all components of window1, e.g. mouse clicks, and show it.
		cvui.update(WINDOW1_NAME)
		cv2.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.
		# We do that by calling cvui.context().
		cvui.context(WINDOW2_NAME)
		frame2[:] = (49, 52, 49)
		
		cvui.beginRow(frame2, 10, 20, 100, 50)
		cvui.text('This is ')
		cvui.printf('a row')
		cvui.checkbox('checkbox', window2_checked)
		cvui.window(80, 80, 'window')
		cvui.rect(50, 50, 0x00ff00, 0xff0000)
		cvui.sparkline(window2_values, 50, 50)
		cvui.counter(window2_value)
		cvui.button(100, 30, 'Fixed')
		cvui.image(img)
		cvui.button(img, imgGray, imgRed)
		cvui.endRow()
		
		padding = 50
		cvui.beginRow(frame2, 10, 150, 100, 50, padding)
		cvui.text('This is ')
		cvui.printf('another row')
		cvui.checkbox('checkbox', window2_checked2)
		cvui.window(80, 80, 'window')
		cvui.button(100, 30, 'Fixed')
		cvui.printf('with 50px paddin7hg.')
		cvui.endRow()
		
		# Another row mixing several components 
		cvui.beginRow(frame2, 10, 250, 100, 50)
		cvui.text('This is ')
		cvui.printf('another row with a trackbar ')
		cvui.trackbar(150, window2_value2, 0., 5.)
		cvui.printf(' and a button ')
		cvui.button(100, 30, 'button')
		cvui.endRow()

		cvui.beginColumn(frame2, 50, 330, 100, 200)
		cvui.text('Column 1 (no padding)')
		cvui.button('button1')
		cvui.button('button2')
		cvui.text('End of column 1')
		cvui.endColumn()
		
		padding = 10
		cvui.beginColumn(frame2, 300, 330, 100, 200, padding)
		cvui.text('Column 2 (padding = 10)')
		cvui.button('button1')
		cvui.button('button2')
		cvui.trackbar(150, window2_value3, 0., 5., 1, '%3.2Lf', cvui.TRACKBAR_DISCRETE, 0.25)
		cvui.text('End of column 2')
		cvui.endColumn()

		cvui.beginColumn(frame2, 550, 330, 100, 200)
		cvui.text('Column 3 (use space)')
		cvui.space(5)
		cvui.button('button1 5px below')
		cvui.space(50)
		cvui.text('Text 50px below')
		cvui.space(20)
		cvui.button('Button 20px below')
		cvui.space(40)
		cvui.text('End of column 2 (40px below)')
		cvui.endColumn()
		
		# Update all components of window2, e.g. mouse clicks, and show it.
		cvui.update(WINDOW2_NAME)
		cv2.imshow(WINDOW2_NAME, frame2)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
示例#24
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
示例#25
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()
示例#26
0
文件: main-app.py 项目: Dovyski/cvui
def main():
	frame = np.zeros((300, 600, 3), np.uint8)
	checked = [False]
	checked2 = [True]
	count = [0]
	countFloat = [0.0]
	trackbarValue = [0.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)

		# Show some pieces of text.
		cvui.text(frame, 50, 30, 'Hey there!')
		
		# You can also specify the size of the text and its color
		# using hex 0xRRGGBB CSS-like style.
		cvui.text(frame, 200, 30, 'Use hex 0xRRGGBB colors easily', 0.4, 0xff0000)
		
		# 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.
		cvui.printf(frame, 200, 50, 0.4, 0x00ff00, 'Use printf formatting: %d + %.2f = %f', 2, 3.2, 5.2)

		# Buttons will return true if they were clicked, which makes
		# handling clicks a breeze.
		if cvui.button(frame, 50, 60, 'Button'):
			print('Button clicked')

		# If you do not specify the button width/height, the size will be
		# automatically adjusted to properly house the label.
		cvui.button(frame, 200, 70, 'Button with large label')
		
		# You can tell the width and height you want
		cvui.button(frame, 410, 70, 15, 15, 'x')

		# Window components are useful to create HUDs and similars. At the
		# moment, there is no implementation to constraint content within a
		# a window.
		cvui.window(frame, 50, 120, 120, 100, 'Window')
		
		# The counter component can be used to alter int variables. Use
		# the 4th parameter of the function to point it to the variable
		# to be changed.
		cvui.counter(frame, 200, 120, count)

		# Counter can be used with doubles too. You can also specify
		# the counter's step (how much it should change
		# its value after each button press), as well as the format
		# used to print the value.
		cvui.counter(frame, 320, 120, countFloat, 0.1, '%.1f')

		# The trackbar component can be used to create scales.
		# It works with all numerical types (including chars).
		cvui.trackbar(frame, 420, 110, 150, trackbarValue, 0., 50.)
		
		# Checkboxes also accept a pointer to a variable that controls
		# the state of the checkbox (checked or not). cvui.checkbox() will
		# automatically update the value of the boolean after all
		# interactions, but you can also change it by yourself. Just
		# do "checked = [True]" somewhere and the checkbox will change
		# its appearance.
		cvui.checkbox(frame, 200, 160, 'Checkbox', checked)
		cvui.checkbox(frame, 200, 190, 'A checked checkbox', checked2)

		# Display the lib version at the bottom of the screen
		cvui.printf(frame, 600 - 80, 300 - 20, 0.4, 0xCECECE, 'cvui v.%s', cvui.VERSION)

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
示例#27
0
def main():
	intValue = [30]
	ucharValue = [30]
	charValue = [30]
	floatValue = [12.]
	doubleValue1 = [15.]
	doubleValue2 = [10.3]
	doubleValue3 = [2.25]
	frame = np.zeros((650, 450, 3), np.uint8)

	# Size of trackbars
	width = 400

	# Init cvui and tell it to use a value of 20 for cv2.waitKey()
	# because we want to enable keyboard shortcut for
	# all components, e.g. button with label '&Quit'.
	# If cvui has a value for waitKey, it will call
	# waitKey() automatically for us within cvui.update().
	cvui.init(WINDOW_NAME, 20)

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

		cvui.beginColumn(frame, 20, 20, -1, -1, 6)
		
		cvui.text('int trackbar, no customization')
		cvui.trackbar(width, intValue, 0, 100)
		cvui.space(5)

		cvui.text('uchar trackbar, no customization')
		cvui.trackbar(width, ucharValue, 0, 255)
		cvui.space(5)

		cvui.text('signed char trackbar, no customization')
		cvui.trackbar(width, charValue, -128, 127)
		cvui.space(5)

		cvui.text('float trackbar, no customization')
		cvui.trackbar(width, floatValue, 10., 15.)
		cvui.space(5)

		cvui.text('float trackbar, 4 segments')
		cvui.trackbar(width, doubleValue1, 10., 20., 4)
		cvui.space(5)

		cvui.text('double trackbar, label %.1Lf, TRACKBAR_DISCRETE')
		cvui.trackbar(width, doubleValue2, 10., 10.5, 1, '%.1Lf', cvui.TRACKBAR_DISCRETE, 0.1)
		cvui.space(5)

		cvui.text('double trackbar, label %.2Lf, 2 segments, TRACKBAR_DISCRETE')
		cvui.trackbar(width, doubleValue3, 0., 4., 2, '%.2Lf', cvui.TRACKBAR_DISCRETE, 0.25)
		cvui.space(10)

		# Exit the application if the quit button was pressed.
		# It can be pressed because of a mouse click or because 
		# the user pressed the 'q' key on the keyboard, which is
		# marked as a shortcut in the button label ('&Quit').
		if cvui.button('&Quit'):
			break
		
		cvui.endColumn()

		# Since cvui.init() received a param regarding waitKey,
		# there is no need to call cv.waitKey() anymore. cvui.update()
		# will do it automatically.
		cvui.update()

		cv2.imshow(WINDOW_NAME, frame)
示例#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
    def run(self):

        self.main_frame = np.zeros((380, 400, 3), np.uint8)

        cv.namedWindow(self.main_window_name)
        cvui.init(self.main_window_name)

        while True:

            cvui.context(self.main_window_name)

            self.main_frame[:] = (49, 52, 49)

            cvui.beginColumn(self.main_frame, 50, 20, -1, -1, 10)

            cvui.text('Click to open an image')

            if cvui.button('Select Image'):
                self.load_image()

            cvui.text('Load a previously saved txt file to current image')

            if cvui.button("Read Txt file"):
                self.read_txt()

            cvui.text('Save to txt file')

            if cvui.button('Save'):
                self.save_to_txt()

            if cvui.button("Show/Hide Index"):
                self.has_index = not self.has_index

            if cvui.button("Clear All Points"):
                self.points.clear()
                self.high_light_point = None

            cvui.text('Max click distance to select one point')
            cvui.text('adjust smaller if you want to click two close points')
            cvui.trackbar(200, self.threshold, 0.000, 0.02, 2, '%.4Lf')

            cvui.endColumn()

            cvui.update(self.main_window_name)
            cv.imshow(self.main_window_name, self.main_frame)

            key = cv.waitKey(20)
            if key == 27 or not self.is_window_open(self.main_window_name):
                self.tkinter_root.destroy()
                break

            if self.is_window_open(self.image_window_name):

                cvui.context(self.image_window_name)

                self.show_image = cv.resize(
                    self.origin_image, (self.actual_width, self.actual_height))

                for i, point in enumerate(self.points):
                    if i not in self.deleted_list:
                        self.draw_intersection(self.show_image, point, i)

                if self.high_light_point is not None:
                    point = self.points[self.high_light_point]
                    cv.circle(self.show_image,
                              (int(point[0] * self.actual_width),
                               int(point[1] * self.actual_height)), 5,
                              (0, 255, 255), 1)

                # Fill the error window if a vibrant color
                # if self.image_window_flag:

                cvui.update(self.image_window_name)
                cv.imshow(self.image_window_name, self.show_image)

                self.keyboard(key)
示例#30
0
def main():
	lena = cv2.imread('lena.jpg')
	frame = np.zeros(lena.shape, np.uint8)
	anchors = [cvui.Point() for i in range(3)]   # one anchor for each mouse button
	rois = [cvui.Rect() for i in range(3)]       # one ROI for each mouse button
	colors = [0xff0000, 0x00ff00, 0x0000ff]

	# 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 Lena's image
		frame[:] = lena[:]

		# Show the coordinates of the mouse pointer on the screen
		cvui.text(frame, 10, 10, 'Click (any) mouse button then drag the pointer around to select a ROI.')
		cvui.text(frame, 10, 25, 'Use different mouse buttons (right, middle and left) to select different ROIs.')

		# Iterate all mouse buttons (left, middle  and right button)
		button = cvui.LEFT_BUTTON
		while button <= cvui.RIGHT_BUTTON:
			# Get the anchor, ROI and color associated with the mouse button
			anchor = anchors[button]
			roi = rois[button]
			color = colors[button]

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

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

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

				roi.x = anchor.x + width if width < 0 else anchor.x
				roi.y = anchor.y + height if height < 0 else anchor.y
				roi.width = abs(width)
				roi.height = abs(height)

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

			# Ensure ROI is within bounds
			lenaRows, lenaCols, lenaChannels = lena.shape
			roi.x = 0 if roi.x < 0 else roi.x
			roi.y = 0 if roi.y < 0 else roi.y
			roi.width = roi.width + lenaCols - (roi.x + roi.width) if roi.x + roi.width > lenaCols else roi.width
			roi.height = roi.height + lenaRows - (roi.y + roi.height) if roi.y + roi.height > lenaRows else roi.height

			# If the ROI is valid, render it in the frame and show in a window.
			if roi.area() > 0:
				cvui.rect(frame, roi.x, roi.y, roi.width, roi.height, color)
				cvui.printf(frame, roi.x + 5, roi.y - 10, 0.3, color, 'ROI %d', button)

				lenaRoi = lena[roi.y : roi.y + roi.height, roi.x : roi.x + roi.width]
				cv2.imshow('ROI button' + str(button), lenaRoi)

			button += 1

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
    displ = left_matcher.compute(grayLeft, grayRight)  #.astype(np.float32)/16
    displ = np.int16(displ)

    filteredImg = cv2.normalize(src=displ,
                                dst=None,
                                beta=0,
                                alpha=255,
                                norm_type=cv2.NORM_MINMAX,
                                dtype=cv2.CV_8UC1)
    filteredImg = cv2.applyColorMap(filteredImg, cv2.COLORMAP_BONE)

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

    cvui.text(frame, 50, 20, 'Block Size: ')
    cvui.trackbar(frame, 25, 40, 600, blockSize, 5, 101, 2, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 2)

    cvui.text(frame, 50, 90, 'numDisparites')
    cvui.trackbar(frame, 25, 110, 600, numDisparities, 16, 198, 16, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 16)

    cvui.text(frame, 50, 160, 'P1: ')
    cvui.trackbar(frame, 25, 180, 600, P1, 0, 100, 1, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 1)

    cvui.text(frame, 50, 230, 'P2 (should be larger than p2: ')
    cvui.trackbar(frame, 25, 250, 600, P2, 0, 3000, 1, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 1)
def main():
	frame = np.zeros((600, 800, 3), np.uint8)
	values = []
	checked = [False]
	value = [1.0]

	# Fill the vector with a few random values
	for i in range(0, 20):
		values.append(random.uniform(0., 300.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)

		# Define a row at position (10, 50) with width 100 and height 150.
		cvui.beginRow(frame, 10, 50, 100, 150)
		# The components below will be placed one beside the other.
		cvui.text('Row starts')
		cvui.button('here')

		# When a column or row is nested within another, it behaves like
		# an ordinary component with the specified size. In this case,
		# let's create a column with width 100 and height 50. The
		# next component added will behave like it was added after
		# a component with width 100 and heigth 150.
		cvui.beginColumn(100, 150)
		cvui.text('Column 1')
		cvui.button('button1')
		cvui.button('button2')
		cvui.button('button3')
		cvui.text('End of column 1')
		cvui.endColumn()

		# Add two pieces of text
		cvui.text('Hi again,')
		cvui.text('its me!')

		# Start a new column
		cvui.beginColumn(100, 50)
		cvui.text('Column 2')
		cvui.button('button1')
		cvui.button('button2')
		cvui.button('button3')
		cvui.space()
		cvui.text('Another text')
		cvui.space(40)
		cvui.text('End of column 2')
		cvui.endColumn()

		# Add more text
		cvui.text('this is the ')
		cvui.text('end of the row!')
		cvui.endRow()

		# Here is another nested row/column
		cvui.beginRow(frame, 50, 300, 100, 150)
		
		# If you don't want to calculate the size of any row/column WITHIN
		# a begin*()/end*() block, just use negative width/height when
		# calling beginRow() or beginColumn() (or don't provide width/height at all!)

		# For instance, the following column will have its width/height
		# automatically adjusted according to its content.
		cvui.beginColumn()
		cvui.text('Column 1')
		cvui.button('button with very large label')
		cvui.text('End of column 1')
		cvui.endColumn()

		# Add two pieces of text
		cvui.text('Hi again,')
		cvui.text('its me!')

		# Start a new column
		cvui.beginColumn()
		cvui.text('Column 2')
		cvui.button('btn')
		cvui.space()
		cvui.text('text')
		cvui.button('btn2')
		cvui.text('text2')
		if cvui.button('&Quit'):
			break
		cvui.endColumn()

		# Add more text
		cvui.text('this is the ')
		cvui.text('end of the row!')
		cvui.endRow()

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
示例#33
0
def page1():
    cvui.text(frame1, int(0.2*width), int(.4*height), "Waiting for the Inspection...",(0.002*height), 0x000000)
示例#34
0
def galileo(frame, expr):
    curr_expr = expr
    experiments = [[False] for i in range(2)]

    restart = True
    distance_tr = [1.1]

    galileo_default = cv2.imread(resource_path("images/galileo_default.png"),
                                 3)
    galileo_yellow_dot = cv2.imread(
        resource_path("images/galileo_yellow_dot.png"), 3)
    galileo_fire = cv2.imread(resource_path("images/galileo_fire.png"), 3)

    while (True):
        frame[:] = (49, 52, 49)

        if restart:
            animation = 0
            animate = False
            galileo_coord_bottom = 385
            galileo_coord_top = 985
            first_graph_f = False
            second_graph_f = False
            first_graph = False
            second_graph = False
            first_delay = 0
            second_delay = 0
            delay = 0
            speed_of_light = 299792
            half = False
            first_after_half = 0
            first_after_end = 0
            restart = False
            static_distance = False

        if not first_graph_f:
            first_graph, lag = get_graph()
            first_delay = lag
            first_graph_f = True
        if not second_graph_f:
            second_graph, lag = get_graph()
            second_delay = lag
            second_graph_f = True

        #Animation window
        cvui.image(frame, 0, 0, galileo_default)

        if animate:
            galileo_coord_bottom = 368
            galileo_coord_top = 968
            cvui.image(frame, 314, 393, galileo_fire)
            if animation < 21:
                for _ in range(animation + 1):
                    cvui.image(frame, galileo_coord_bottom, 400,
                               galileo_yellow_dot)
                    galileo_coord_bottom = galileo_coord_bottom + 30
            else:
                for _ in range(21):
                    cvui.image(frame, galileo_coord_bottom, 400,
                               galileo_yellow_dot)
                    galileo_coord_bottom = galileo_coord_bottom + 30

            if animation >= 21 and animation < 42:
                cvui.image(frame, 960, 200, first_graph)
                cvui.text(frame, 1045, 186, "Reaction delay", 0.4)
                cvui.text(frame, 1079, 278, str(int(first_delay)) + "ms", 0.4)

                cvui.image(frame, 1036, 390, galileo_fire)
                for _ in range(animation + 1 - 21):
                    cvui.image(frame, galileo_coord_top, 375,
                               galileo_yellow_dot)
                    galileo_coord_top = galileo_coord_top - 30
            elif animation == 42:
                if first_after_end != 0:
                    if (timer() - first_after_end) > (second_delay / 1000):
                        first_after_end = 0
                        cvui.image(frame, 131, 205, second_graph)
                        cvui.text(frame, 216, 191, "Reaction delay", 0.4)
                        cvui.text(frame, 248, 285,
                                  str(int(second_delay)) + "ms", 0.4)
                        delay = static_distance / speed_of_light + (
                            first_delay / 1000) + (second_delay / 1000)
                else:
                    cvui.image(frame, 131, 205, second_graph)
                    cvui.text(frame, 216, 191, "Reaction delay", 0.4)
                    cvui.text(frame, 248, 285,
                              str(int(second_delay)) + "ms", 0.4)

                cvui.image(frame, 1036, 390, galileo_fire)
                for _ in range(21):
                    cvui.image(frame, galileo_coord_top, 375,
                               galileo_yellow_dot)
                    galileo_coord_top = galileo_coord_top - 30

            if animation < 42:
                act_time = timer() - start_time
                whole_distance = static_distance
                if half:
                    traveled_distance = (act_time -
                                         (first_delay / 1000)) * speed_of_light
                else:
                    traveled_distance = act_time * speed_of_light
                piece_of_distance = whole_distance / 21
                traveled_parts = traveled_distance / piece_of_distance
                if first_after_half != 0:
                    if (timer() - first_after_half) > (first_delay / 1000):
                        first_after_half = 0
                else:
                    if not half:
                        if traveled_parts >= 21:
                            animation = 20
                            half = True
                            first_after_half = timer()
                        else:
                            animation = int(traveled_parts)
                    else:
                        if traveled_parts >= 42:
                            animation = 42
                            first_after_end = timer()
                        else:
                            animation = int(traveled_parts)
            else:
                cvui.image(frame, 960, 200, first_graph)
                cvui.text(frame, 1045, 186, "Reaction delay", 0.4)
                cvui.text(frame, 1079, 278, str(int(first_delay)) + "ms", 0.4)
                if delay != 0:
                    cvui.text(frame, 640, 320, "Total time", 0.5)
                    cvui.text(frame, 660, 343, str(round(delay, 2)) + "s", 0.5)
                    cvui.text(frame, 345, 60,
                              "Calculation of the speed of light", 0.5)
                    cvui.text(
                        frame, 345, 80,
                        "distance between mountains ... s = {:,} km".format(
                            static_distance / 2), 0.5)
                    cvui.text(frame, 345, 100,
                              "average human reaction time ... d = 250 ms",
                              0.5)
                    cvui.text(
                        frame, 345, 120,
                        "c=(2*s)/(t-2*d)=(2*{:,})/({}-2*0.25)={:,} km/s".
                        format(
                            static_distance / 2, str(round(delay, 2)),
                            round(
                                static_distance / (round(delay, 2) - 2 * 0.25),
                                2)), 0.5)

        if delay == 0:
            cvui.text(frame, 345, 60, "Calculation of the speed of light", 0.5)
            if static_distance:
                cvui.text(
                    frame, 345, 80,
                    "distance between mountains ... s = {:,} km".format(
                        static_distance / 2), 0.5)
            else:
                cvui.text(
                    frame, 345, 80,
                    "distance between mountains ... s = {:,} km".format(
                        round((distance_tr[0])**8, 0)), 0.5)
            cvui.text(frame, 345, 100,
                      "average human reaction time ... d = 250 ms", 0.5)
            cvui.text(frame, 345, 120,
                      "c=(2*s)/(t-2*d) ... total time wasn't measured", 0.5)

        #Experiment settings window
        cvui.window(frame, 1033.5, 2, 243.5, 133, 'Experiment settings')

        cvui.trackbar(frame, 1030, 39, 249, distance_tr, 1.1, 10.0)
        cvui.rect(frame, 1035, 39, 240, 12, 0x313131, 0x313131)
        cvui.rect(frame, 1035, 74, 240, 25, 0x313131, 0x313131)
        cvui.text(frame, 1041, 32, "Distance")
        cvui.text(frame, 1042, 82,
                  "{:,} km".format(round((distance_tr[0])**8, 0)))
        if cvui.button(frame, 1040, 102, "Measure time"):
            if not animate:
                static_distance = round((distance_tr[0])**8, 0) * 2
            animate = True
            start_time = timer()
        if cvui.button(frame, 1161, 102, "Clear"):
            restart = True

        #Experiments window
        cvui.window(frame, 2, 2, 155, 75, 'Experiments')

        cvui.checkbox(frame, 10, 30, "1638 - Galileo", experiments[0])
        cvui.checkbox(frame, 10, 53, "1849 - Fizeau", experiments[1])

        curr_expr = exp_type(curr_expr, experiments)
        experiments = [[False] for i in range(2)]
        experiments[curr_expr] = [True]

        cvui.update()

        cv2.imshow('Speed of Light Measurement', frame)

        if cv2.waitKey(20) == 27:
            return -1

        if curr_expr != expr:
            return curr_expr
示例#35
0
def page3(date,pcount,mimg,simg):
    tpic=cv2.imread(mimg)
    tpic=imutils.resize(tpic, height=int(height*.84))
    [ty,tx,aa]=tpic.shape
    frame1[int(0.075*height):int(0.075*height)+ty, int(.01*width):int(.01*width)+tx]=tpic
    ipic=cv2.imread(simg)
    ipic=imutils.resize(ipic, height=int(height*.3))
    [iy,ix,aa]=ipic.shape
    frame1[int(0.15*height):int(0.15*height)+iy, int(.73*width):int(.73*width)+ix]=ipic
    bpic=cv2.imread("masterdata/datebg.png")
    bpic=imutils.resize(bpic, width=int(width*.28))
    [by,bx,ba]=bpic.shape
    frame1[int(0.71*height):int(0.71*height)+by, int(.72*width):int(.72*width)+bx]=bpic           
    cvui.text(frame1, int(0.75*width), int(.5*height), "Outer sealing",(0.001*height), 0x000000)
    cvui.text(frame1, int(0.75*width), int(.55*height), "Large Fuse",(0.001*height), 0x000000)
    cvui.text(frame1, int(0.75*width), int(.6*height), "Small Fuse",(0.001*height), 0x000000)
    cvui.text(frame1, int(0.75*width), int(.65*height), "Heatshrink",(0.001*height), 0x000000)
    cvui.text(frame1, int(0.72*width), int(.75*height), date,(0.001*height), 0x000000)
    cvui.text(frame1, int(0.72*width), int(.81*height), pcount,(0.001*height), 0x000000)
示例#36
0
def teach_step(posed='Images/yoga.jpg', Check=False):
    Estimator = TfPoseEstimator
    frame1 = np.zeros((768, 1024, 3), np.uint8)

    WINDOW1_NAME = 'Dance Dance Pose'
    cv2.namedWindow(WINDOW1_NAME)
    cvui.init(WINDOW1_NAME)

    inferred = infer(posed)
    original = cv2.imread(posed)

    #time.sleep(5)
    if original.shape[0] != 480 or original.shape[1] != 640:
        original = cv2.resize(original, (368, 368))

    if Check:
        cv2.imwrite('check.jpg', inferred)

    inferred = inferred - original
    #inferred=cv2.copyMakeBorder(inferred[:,int(np.nonzero(inferred)[1][0]/2):],0,0,0,int(np.nonzero(inferred)[1][0]/2),cv2.BORDER_REPLICATE)

    timeout = time.time() + 10
    capture = cv2.VideoCapture(0)
    counter = [time.time()]
    x = 1

    while True:
        cvui.context(WINDOW1_NAME)

        ret, frame = capture.read()

        gray = frame
        if gray.shape[0] != 4810 or gray.shape[1] != 640:
            gray = cv2.resize(gray, (368, 368))

        dst = cv2.addWeighted(inferred, 0.5, gray, 0.5, 0)
        frame1[:] = (49, 52, 49)
        cvui.beginRow(frame1, 10, 20, -1, -1, 30)

        cvui.image(dst)
        cvui.image(original)

        cvui.endRow()

        cvui.beginRow(frame1, 10, 400, -1, -1, 30)
        cvui.counter(frame1, 100, 410, counter, 0.1, '%.1f')
        counter = [timeout - time.time() for x in counter]
        cvui.text(frame1, 10, 410, "Tick tick")
        cvui.endRow()

        cvui.update(WINDOW1_NAME)
        cv2.imshow(WINDOW1_NAME, frame1)

        if cv2.waitKey(1) & 0xFF == ord('q') or time.time() > timeout:

            filename = 'captures/capture' + \
                      str(int(x)) + ".png"
            x = x + 1
            cv2.imwrite(filename, frame)
            break

    inferred_capture = infer(filename)
    original_inferred = cv2.imread(filename)

    if original_inferred.shape[0] != 4380 or original_inferred.shape[1] != 640:
        inferred_capture = cv2.resize(inferred_capture, (368, 368))
        original_inferred = cv2.resize(original_inferred, (368, 368))

    while True:
        final = cv2.addWeighted(inferred, 0.5, inferred_capture, 0.5, 0)
        cv2.imshow('final', final)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    diff_inferred = inferred_capture - original_inferred
    bw_inferred = cv2.cvtColor(diff_inferred, cv2.COLOR_BGR2GRAY)
    bw_inferred[bw_inferred >= 1] = 1
    bw_inferred[bw_inferred < 1] = 0

    bw_orig_inferred = cv2.cvtColor(inferred, cv2.COLOR_BGR2GRAY)
    bw_orig_inferred[bw_orig_inferred >= 1] = 1
    bw_orig_inferred[bw_orig_inferred < 1] = 0
    total = bw_orig_inferred == bw_inferred

    print('')
    print('')
    print('Overlap:' + str((1 - np.sum(total) / np.size(total)) * 10))
示例#37
0
def main():
    lena = cv2.imread('lena.jpg')
    frame = np.zeros(lena.shape, np.uint8)
    anchor = cvui.Point()
    roi = cvui.Rect(0, 0, 0, 0)
    working = False

    # 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 Lena's image
        frame[:] = lena[:]

        # Show the coordinates of the mouse pointer on the screen
        cvui.text(
            frame, 10, 10,
            'Click (any) mouse button and drag the pointer around to select a ROI.'
        )

        # 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 single frame only.
        #	- cvui.UP: any mouse button was released. cvui.mouse() returns true for 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 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 anchor at the mouse pointer.
            anchor.x = cvui.mouse().x
            anchor.y = cvui.mouse().y

            # Inform we are working, so the ROI window is not updated every frame
            working = True

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

            roi.x = anchor.x + width if width < 0 else anchor.x
            roi.y = anchor.y + height if height < 0 else anchor.y
            roi.width = abs(width)
            roi.height = abs(height)

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

        # Was the mouse clicked (any button went down then up)?
        if cvui.mouse(cvui.UP):
            # We are done working with the ROI.
            working = False

        # Ensure ROI is within bounds
        lenaRows, lenaCols, lenaChannels = lena.shape
        roi.x = 0 if roi.x < 0 else roi.x
        roi.y = 0 if roi.y < 0 else roi.y
        roi.width = roi.width + lena.cols - (
            roi.x + roi.width) if roi.x + roi.width > lenaCols else roi.width
        roi.height = roi.height + lena.rows - (
            roi.y +
            roi.height) if roi.y + roi.height > lenaRows else roi.height

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

        # This function must be called *AFTER* all UI components. It does
        # all the behind the scenes magic to handle mouse clicks, etc.
        cvui.update()

        # Show everything on the screen
        cv2.imshow(WINDOW_NAME, frame)

        # If the ROI is valid, show it.
        if roi.area() > 0 and working == False:
            lenaRoi = lena[roi.y:roi.y + roi.height, roi.x:roi.x + roi.width]
            cv2.imshow(ROI_WINDOW, lenaRoi)

        # 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")
示例#39
0
def draw_settings(ctrl_frame, control_panes, canny_state, threshold_state,
                  stage_mode, focus_mode, tracker_mode):

    # define the mutually-exclusive mode toggles

    stage_manual = [stage_mode == 'MANUAL']
    stage_auto = [stage_mode == 'AUTO']
    stage_paused = [stage_mode == 'PAUSED']

    focus_manual = [focus_mode == 'MANUAL']
    focus_sharpness = [focus_mode == 'SHARPNESS']
    focus_depth = [focus_mode == 'DEPTH']

    tracker_box_kcf = [tracker_mode == 'KCF']
    tracker_box_canny = [tracker_mode == 'CANNY']
    tracker_box_threshold = [tracker_mode == 'THRESHOLD']
    macro_resweep = False
    ll_resweep = False

    control_panes.stage_control_pane.begin(ctrl_frame)
    if not control_panes.stage_control_pane.isMinimized():
        cvui.space(100)  # add 20px of empty space
        cvui.checkbox('Stage Paused', stage_paused)
        cvui.checkbox('Stage Manual', stage_manual)
        cvui.checkbox('Stage Auto', stage_auto)
    control_panes.stage_control_pane.end()

    control_panes.focus_control_pane.begin(ctrl_frame)
    if not control_panes.focus_control_pane.isMinimized():
        cvui.space(80)  # add 20px of empty space
        cvui.checkbox('Focus Manual', focus_manual)
        cvui.checkbox('Focus Sharpness', focus_sharpness)
        cvui.checkbox('Focus Depth', focus_depth)
    control_panes.focus_control_pane.end()

    control_panes.tracker_select_pane.begin(ctrl_frame)
    if not control_panes.tracker_select_pane.isMinimized():
        cvui.space(60)  # add 20px of empty space
        cvui.checkbox('KCF Tracker', tracker_box_kcf)
        cvui.checkbox('Canny Tracker', tracker_box_canny)
        cvui.checkbox('Threshold Tracker', tracker_box_threshold)
    control_panes.tracker_select_pane.end()

    control_panes.canny_settings_pane.begin(ctrl_frame)
    if not control_panes.canny_settings_pane.isMinimized():
        cvui.space(40)  # add 20px of empty space
        cvui.text('Canny Low Threshold')
        cvui.trackbar(control_panes.canny_settings_pane.width() - 20,
                      canny_state.canny_low, 5, 150)
        cvui.text('Canny High Threshold')
        cvui.trackbar(control_panes.canny_settings_pane.width() - 20,
                      canny_state.canny_high, 80, 300)
    control_panes.canny_settings_pane.end()

    control_panes.threshold_setting_pane.begin(ctrl_frame)
    if not control_panes.threshold_setting_pane.isMinimized():
        cvui.space(20)  # add 20px of empty space
        cvui.text('Binarization Threshold')
        cvui.trackbar(control_panes.threshold_setting_pane.width() - 20,
                      threshold_state.threshold, 0, 255)
        cvui.checkbox('Show Binary Image', threshold_state.show_binary)
        cvui.text('MOVE THESE!!!!')
        if cvui.button('Force Macro Focus Sweep'):
            macro_resweep = True
        else:
            macro_resweep = False
        if cvui.button('Liquid Lens Focus Sweep'):
            ll_resweep = True
        else:
            ll_resweep = False
    control_panes.threshold_setting_pane.end()

    if stage_manual[0] and not stage_mode == 'MANUAL':
        stage_mode = 'MANUAL'
    elif stage_auto[0] and not stage_mode == 'AUTO':
        stage_mode = 'AUTO'
    elif stage_paused[0] and not stage_mode == 'PAUSED':
        stage_mode = 'PAUSED'

    if focus_manual[0] and not focus_mode == 'MANUAL':
        focus_mode = 'MANUAL'
    elif focus_sharpness[0] and not focus_mode == 'SHARPNESS':
        focus_mode = 'SHARPNESS'
    elif focus_depth[0] and not focus_mode == 'DEPTH':
        focus_mode = 'DEPTH'

    if tracker_box_kcf[0] and not tracker_mode == 'KCF':
        tracker_mode = 'KCF'
    elif tracker_box_canny[0] and not tracker_mode == 'CANNY':
        tracker_mode = 'CANNY'
    elif tracker_box_threshold and not tracker_mode == 'THRESHOLD':
        tracker_mode = 'THRESHOLD'

    return stage_mode, focus_mode, tracker_mode, macro_resweep, ll_resweep
示例#40
0
def main():
	lena = cv2.imread('lena.jpg')
	frame = np.zeros(lena.shape, np.uint8)
	anchor = cvui.Point()
	roi = cvui.Rect(0, 0, 0, 0)
	working = False

	# 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 Lena's image
		frame[:] = lena[:]

		# Show the coordinates of the mouse pointer on the screen
		cvui.text(frame, 10, 10, 'Click (any) mouse button and drag the pointer around to select a ROI.')

		# 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 single frame only.
		#	- cvui.UP: any mouse button was released. cvui.mouse() returns true for 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 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 anchor at the mouse pointer.
			anchor.x = cvui.mouse().x
			anchor.y = cvui.mouse().y

			# Inform we are working, so the ROI window is not updated every frame
			working = True

		# Is any mouse button down (pressed)?
		if cvui.mouse(cvui.IS_DOWN):
			# Adjust roi dimensions according to mouse pointer
			width = cvui.mouse().x - anchor.x
			height = cvui.mouse().y - anchor.y
			
			roi.x = anchor.x + width if width < 0 else anchor.x
			roi.y = anchor.y + height if height < 0 else anchor.y
			roi.width = abs(width)
			roi.height = abs(height)

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

		# Was the mouse clicked (any button went down then up)?
		if cvui.mouse(cvui.UP):
			# We are done working with the ROI.
			working = False

		# Ensure ROI is within bounds
		lenaRows, lenaCols, lenaChannels = lena.shape
		roi.x = 0 if roi.x < 0 else roi.x
		roi.y = 0 if roi.y < 0 else roi.y
		roi.width = roi.width + lena.cols - (roi.x + roi.width) if roi.x + roi.width > lenaCols else roi.width
		roi.height = roi.height + lena.rows - (roi.y + roi.height) if roi.y + roi.height > lenaRows else roi.height

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

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# If the ROI is valid, show it.
		if roi.area() > 0 and working == False:
			lenaRoi = lena[roi.y : roi.y + roi.height, roi.x : roi.x + roi.width]
			cv2.imshow(ROI_WINDOW, lenaRoi)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break
    dispr = np.int16(dispr)

    filteredImg = wls_filter.filter(displ, fixedLeft, None,
                                    dispr)  # important to put "imgL" here!!!
    filteredImg = cv2.normalize(src=filteredImg,
                                dst=filteredImg,
                                beta=0,
                                alpha=255,
                                norm_type=cv2.NORM_MINMAX)
    filteredImg = np.uint8(filteredImg)
    filteredImg = cv2.applyColorMap(filteredImg, cv2.COLORMAP_BONE)

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

    cvui.text(frame, 50, 20, 'Block Size: ')
    cvui.trackbar(frame, 25, 40, 600, blockSize, 5, 101, 2, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 2)

    cvui.text(frame, 50, 120, 'minDisparites from -100 to ')
    cvui.trackbar(frame, 25, 140, 600, numDisparities, 0, 198, 16, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 16)

    cvui.text(frame, 50, 220, 'Uniqueness Ratio: ')
    cvui.trackbar(frame, 25, 240, 600, uniquessRatio, 0, 100, 1, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 1)

    cvui.text(frame, 50, 320, 'speckleRange: ')
    cvui.trackbar(frame, 25, 340, 600, speckleRange, 0, 100, 1, '%.1Lf',
                  cvui.TRACKBAR_DISCRETE, 1)
def main():
    frame = np.zeros((600, 800, 3), np.uint8)

    # Create variables used by some components
    values = []
    checked = [False]
    checked2 = [False]
    value = [1.0]
    value2 = [1.0]
    value3 = [1.0]
    padding = 10
    img = cv2.imread('lena-face.jpg', cv2.IMREAD_COLOR)
    imgRed = cv2.imread('lena-face-red.jpg', cv2.IMREAD_COLOR)
    imgGray = cv2.imread('lena-face-gray.jpg', cv2.IMREAD_COLOR)

    # Fill the vector with a few random values
    for i in range(0, 20):
        values.append(random.uniform(0., 300.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)

        # In a row, all added elements are
        # horizontally placed, one next the other (from left to right)
        #
        # Within the cvui.beginRow() and cvui.endRow(),
        # all elements will be automatically positioned by cvui.
        #
        # Notice that all component calls within the begin/end block
        # DO NOT have (x,y) coordinates.
        #
        # Let's create a row at position (10,20) with width 100 and height 50.
        cvui.beginRow(frame, 10, 20, 100, 50)
        cvui.text('This is ')
        cvui.printf('a row')
        cvui.checkbox('checkbox', checked)
        cvui.window(80, 80, 'window')
        cvui.rect(50, 50, 0x00ff00, 0xff0000)
        cvui.sparkline(values, 50, 50)
        cvui.counter(value)
        cvui.button(100, 30, 'Fixed')
        cvui.image(img)
        cvui.button(img, imgGray, imgRed)
        cvui.endRow()

        # Here is another row, this time with a padding of 50px among components.
        padding = 50
        cvui.beginRow(frame, 10, 150, 100, 50, padding)
        cvui.text('This is ')
        cvui.printf('another row')
        cvui.checkbox('checkbox', checked2)
        cvui.window(80, 80, 'window')
        cvui.button(100, 30, 'Fixed')
        cvui.printf('with 50px padding.')
        cvui.endRow()

        # Another row mixing several components
        cvui.beginRow(frame, 10, 250, 100, 50)
        cvui.text('This is ')
        cvui.printf('another row with a trackbar ')
        #cvui.trackbar(150, &value2, 0., 5.);
        cvui.printf(' and a button ')
        cvui.button(100, 30, 'button')
        cvui.endRow()

        # In a column, all added elements are vertically placed,
        # one below the other, from top to bottom. Let's create
        # a column at (50, 300) with width 100 and height 200.
        cvui.beginColumn(frame, 50, 330, 100, 200)
        cvui.text('Column 1 (no padding)')
        cvui.button('button1')
        cvui.button('button2')
        cvui.text('End of column 1')
        cvui.endColumn()

        # Here is another column, using a padding value of 10,
        # which will add an space of 10px between each component.
        padding = 10
        cvui.beginColumn(frame, 300, 330, 100, 200, padding)
        cvui.text('Column 2 (padding = 10)')
        cvui.button('button1')
        cvui.button('button2')
        #cvui.trackbar(150, &value3, 0., 5., 1, '%3.2Lf', cvui.TRACKBAR_DISCRETE, 0.25);
        cvui.text('End of column 2')
        cvui.endColumn()

        # You can also add an arbitrary amount of space between
        # components by calling cvui.space().
        #
        # cvui.space() is aware of context, so if it is used
        # within a beginColumn()/endColumn() block, the space will
        # be vertical. If it is used within a beginRow()/endRow()
        # block, space will be horizontal.
        cvui.beginColumn(frame, 550, 330, 100, 200)
        cvui.text('Column 3 (use space)')
        # Add 5 pixels of (vertical) space.
        cvui.space(5)
        cvui.button('button1 5px below')
        # Add 50 pixels of (vertical) space.
        cvui.space(50)
        cvui.text('Text 50px below')
        # Add 20 pixels of (vertical) space.
        cvui.space(20)
        cvui.button('Button 20px below')
        # Add 40 pixels of (vertical) space.
        cvui.space(40)
        cvui.text('End of column 2 (40px below)')
        cvui.endColumn()

        # This function must be called *AFTER* all UI components. It does
        # all the behind the scenes magic to handle mouse clicks, etc.
        cvui.update()

        # Show everything on the screen
        cv2.imshow(WINDOW_NAME, frame)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
示例#43
0
def main():
    lena = cv2.imread('lena.jpg')
    frame = np.zeros(lena.shape, np.uint8)
    anchors = [cvui.Point()
               for i in range(3)]  # one anchor for each mouse button
    rois = [cvui.Rect() for i in range(3)]  # one ROI for each mouse button
    colors = [0xff0000, 0x00ff00, 0x0000ff]

    # 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 Lena's image
        frame[:] = lena[:]

        # Show the coordinates of the mouse pointer on the screen
        cvui.text(
            frame, 10, 10,
            'Click (any) mouse button then drag the pointer around to select a ROI.'
        )
        cvui.text(
            frame, 10, 25,
            'Use different mouse buttons (right, middle and left) to select different ROIs.'
        )

        # Iterate all mouse buttons (left, middle  and right button)
        button = cvui.LEFT_BUTTON
        while button <= cvui.RIGHT_BUTTON:
            # Get the anchor, ROI and color associated with the mouse button
            anchor = anchors[button]
            roi = rois[button]
            color = colors[button]

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

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

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

                roi.x = anchor.x + width if width < 0 else anchor.x
                roi.y = anchor.y + height if height < 0 else anchor.y
                roi.width = abs(width)
                roi.height = abs(height)

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

            # Ensure ROI is within bounds
            lenaRows, lenaCols, lenaChannels = lena.shape
            roi.x = 0 if roi.x < 0 else roi.x
            roi.y = 0 if roi.y < 0 else roi.y
            roi.width = roi.width + lenaCols - (
                roi.x +
                roi.width) if roi.x + roi.width > lenaCols else roi.width
            roi.height = roi.height + lenaRows - (
                roi.y +
                roi.height) if roi.y + roi.height > lenaRows else roi.height

            # If the ROI is valid, render it in the frame and show in a window.
            if roi.area() > 0:
                cvui.rect(frame, roi.x, roi.y, roi.width, roi.height, color)
                cvui.printf(frame, roi.x + 5, roi.y - 10, 0.3, color, 'ROI %d',
                            button)

                lenaRoi = lena[roi.y:roi.y + roi.height,
                               roi.x:roi.x + roi.width]
                cv2.imshow('ROI button' + str(button), lenaRoi)

            button += 1

        # This function must be called *AFTER* all UI components. It does
        # all the behind the scenes magic to handle mouse clicks, etc.
        cvui.update()

        # Show everything on the screen
        cv2.imshow(WINDOW_NAME, frame)

        # Check if ESC key was pressed
        if cv2.waitKey(20) == 27:
            break
示例#44
0
def main():
	frame = np.zeros((600, 800, 3), np.uint8)
	
	# Create variables used by some components
	values = []
	checked = [False]
	checked2 = [False]
	value = [1.0]
	value2 = [1.0]
	value3 = [1.0]
	padding = 10
	img = cv2.imread('lena-face.jpg', cv2.IMREAD_COLOR)
	imgRed = cv2.imread('lena-face-red.jpg', cv2.IMREAD_COLOR)
	imgGray = cv2.imread('lena-face-gray.jpg', cv2.IMREAD_COLOR)

	# Fill the vector with a few random values
	for i in range(0, 20):
		values.append(random.uniform(0., 300.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)

		# In a row, all added elements are
		# horizontally placed, one next the other (from left to right)
		#
		# Within the cvui.beginRow() and cvui.endRow(),
		# all elements will be automatically positioned by cvui.
		# 
		# Notice that all component calls within the begin/end block
		# DO NOT have (x,y) coordinates. 
		#
		# Let's create a row at position (10,20) with width 100 and height 50.
		cvui.beginRow(frame, 10, 20, 100, 50)
		cvui.text('This is ')
		cvui.printf('a row')
		cvui.checkbox('checkbox', checked)
		cvui.window(80, 80, 'window')
		cvui.rect(50, 50, 0x00ff00, 0xff0000);
		cvui.sparkline(values, 50, 50);
		cvui.counter(value)
		cvui.button(100, 30, 'Fixed')
		cvui.image(img)
		cvui.button(img, imgGray, imgRed)
		cvui.endRow()

		# Here is another row, this time with a padding of 50px among components.
		padding = 50;
		cvui.beginRow(frame, 10, 150, 100, 50, padding)
		cvui.text('This is ')
		cvui.printf('another row')
		cvui.checkbox('checkbox', checked2)
		cvui.window(80, 80, 'window')
		cvui.button(100, 30, 'Fixed')
		cvui.printf('with 50px padding.')
		cvui.endRow()

		# Another row mixing several components 
		cvui.beginRow(frame, 10, 250, 100, 50)
		cvui.text('This is ')
		cvui.printf('another row with a trackbar ')
		#cvui.trackbar(150, &value2, 0., 5.);
		cvui.printf(' and a button ')
		cvui.button(100, 30, 'button')
		cvui.endRow()

		# In a column, all added elements are vertically placed,
		# one below the other, from top to bottom. Let's create
		# a column at (50, 300) with width 100 and height 200.
		cvui.beginColumn(frame, 50, 330, 100, 200)
		cvui.text('Column 1 (no padding)')
		cvui.button('button1')
		cvui.button('button2')
		cvui.text('End of column 1')
		cvui.endColumn()

		# Here is another column, using a padding value of 10,
		# which will add an space of 10px between each component.
		padding = 10
		cvui.beginColumn(frame, 300, 330, 100, 200, padding)
		cvui.text('Column 2 (padding = 10)')
		cvui.button('button1')
		cvui.button('button2')
		#cvui.trackbar(150, &value3, 0., 5., 1, '%3.2Lf', cvui.TRACKBAR_DISCRETE, 0.25);
		cvui.text('End of column 2')
		cvui.endColumn()

		# You can also add an arbitrary amount of space between
		# components by calling cvui.space().
		#
		# cvui.space() is aware of context, so if it is used
		# within a beginColumn()/endColumn() block, the space will
		# be vertical. If it is used within a beginRow()/endRow()
		# block, space will be horizontal.
		cvui.beginColumn(frame, 550, 330, 100, 200)
		cvui.text('Column 3 (use space)')
		# Add 5 pixels of (vertical) space.
		cvui.space(5)
		cvui.button('button1 5px below')
		# Add 50 pixels of (vertical) space. 
		cvui.space(50)
		cvui.text('Text 50px below')
		# Add 20 pixels of (vertical) space.
		cvui.space(20)
		cvui.button('Button 20px below')
		# Add 40 pixels of (vertical) space.
		cvui.space(40)
		cvui.text('End of column 2 (40px below)')
		cvui.endColumn()

		# This function must be called *AFTER* all UI components. It does
		# all the behind the scenes magic to handle mouse clicks, etc.
		cvui.update()

		# Show everything on the screen
		cv2.imshow(WINDOW_NAME, frame)

		# Check if ESC key was pressed
		if cv2.waitKey(20) == 27:
			break