def onMouseCheckSubIslands(self, event, x, y, flags, param): ss = param img = ss.image().copy() if not hasattr(self.onMouseCheckSubIslands, "ml"): ml = ANN() islandExist = False if ( event == cv2.EVENT_LBUTTONDOWN ): island = ss.getIslandWithPoint((y,x)) if not island.isEmpty(): lum = img[y,x] area = island.area() shadeNum = ss.getIndexOfShade(island.shade()) nnResult = max(island.nn_results()) img = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) for value in island.coordinates().values(): x = value[1] y = value[0] img[y,x] = (0,255,0) shade_shape = island.shape_name() + "_s" + str(shadeNum) text = "({},{}) | Lum: {} | Area: {} | ShadeShape: {} | NN: {} | {}".format(x,y,lum,area,shade_shape,nnResult,ss.area()) cv2.displayStatusBar(self.winName,text) islandExist = True if(event == cv2.EVENT_LBUTTONUP): img = ss.image().copy() cv2.imshow(self.winName,img) if(islandExist): island.showInteractiveSubIslands()
def edit_mode(self): self.class_id += 1 self.class_id %= len(self.classes) App.win.new = self.classes[self.class_id] print(App.win.new) text = 'Insert new {}'.format(App.win.new.__name__) cv.displayStatusBar(App.win.win, text, 1000)
def update_status_bar(self, current_frame_number, current_shot_number): """Use the status bar to display information.""" fps = self.videodata.frames_per_second status_str = "Shot %d: Frame %d (%.1fs). " % ( current_shot_number + 1, current_frame_number, current_frame_number / fps) surrounding = \ self.testdata.get_surrounding_hit_frames(current_frame_number) if surrounding[0] and surrounding[2]: status_str += "Hits: previous %d (%.1fs), current %d (%.1fs), next %d (%.1fs)" % ( surrounding[0], surrounding[0] / fps, surrounding[1], surrounding[1] / fps, surrounding[2], surrounding[2] / fps) elif surrounding[0]: status_str += "Hits: previous %d (%.1fs), current %d (%.1fs)" % ( surrounding[0], surrounding[0] / fps, surrounding[1], surrounding[1] / fps) elif surrounding[2]: status_str += "Hits: current %d (%.1fs), next %d (%.1fs)" % ( surrounding[1], surrounding[1] / fps, surrounding[2], surrounding[2] / fps) elif surrounding[1]: status_str += "Hits: current %d (%.1fs)" % (surrounding[1], surrounding[1] / fps) else: status_str += "No hits recorded yet." cv2.displayStatusBar("image", status_str, 0)
def mouse_event_handler(event, x, y, flags, param): gt = param rect = gt.gt[gt.pos] x = max(0, min(x, gt.img_size[0] - 1)) y = max(0, min(y, gt.img_size[1] - 1)) if event == cv2.EVENT_LBUTTONDOWN: rect[0] = x rect[1] = y elif event == cv2.EVENT_LBUTTONUP: rect[2] = abs(rect[0] - x) rect[3] = abs(rect[1] - y) if rect[0] > x: rect[0] = x if rect[1] > y: rect[1] = y img = gt.frame.copy() cv2.rectangle(img, (int(rect[0]), int(rect[1])), (int(rect[2] + rect[0]), int(rect[3] + rect[1])), (0, 255, 0), 1) cv2.imshow(gt.img_name, img) cv2.displayStatusBar(gt.img_name, f'{gt.pos} : {rect}') print(gt.pos, rect) if gt.mode == 'cgt_yolo': # # (X1, Y1, W, H) ==> (Cx, Cy, W, H) rect[0] = (rect[0] + rect[2] / 2) / gt.img_size[0] rect[1] = (rect[1] + rect[3] / 2) / gt.img_size[1] rect[2] = rect[2] / gt.img_size[0] rect[3] = rect[3] / gt.img_size[1]
def _update_status_bar(self): # 漢字等の文字があるとdisplayStatusBarがうまくいかないので置換 name = self._current_item.name p = re.compile(r'[\p{Script=Han}〜]+') name = re.sub(p, "_", name) class_ = self._get_class_name(self._current_item.label) text = f"{self._current_index + 1}/{self.img_num} | {name} | {class_}" cv2.displayStatusBar(self.name, text)
def windows_show(self): cvui.update() cvui.context(self.mainwindow_name) cvui.imshow(self.mainwindow_name, self.mainframe) cv2.displayStatusBar( self.mainwindow_name, "{:3.2f}pmm X:{:03d} Y:{:03d} Focus:{:05d} Contours:{:02d} Xmm:{:7.2f} Ymm{:7.2f} Color:{}" .format(self.cal_line_distance_total, self.mouse_x, self.mouse_y, int(self.focus_value), self.contours_found_quan, self.actual_mm_x, self.actual_mm_y, str(self.mouse_color)), 0)
def onMouse(event, x, y, flags, *param): global startpos, crtpos, drag, bboxes crtpos = (x, y) # current mouse position if event == cv2.EVENT_LBUTTONDOWN: startpos = (x, y) drag = True if event == cv2.EVENT_LBUTTONUP: bbox = (startpos, crtpos) bboxes.append(bbox) drag = False # show event message msg = "event:{},x:{},y:{},flags:{}".format(event, x, y, flags) cv2.displayStatusBar(WIN_NAME, msg, 1000)
def update(self) -> None: pan_speed = float(self._pan_speed_manager.current_speed) tilt_speed = float(self._tilt_speed_manager.current_speed) zoom_speed_str = { ZoomSpeed.ZOOM_IN_FAST: 'zoom in fast', ZoomSpeed.ZOOM_IN_SLOW: 'zoom in slow', ZoomSpeed.ZOOM_STOPPED: 'zoom stopped', ZoomSpeed.ZOOM_OUT_SLOW: 'zoom out slow', ZoomSpeed.ZOOM_OUT_FAST: 'zoom out fast', }[self._camera_speeds.zoom_speed] cv2.displayStatusBar( 'Robot Cameraman', f"pan: {pan_speed :3.2}, " f"tilt: {tilt_speed :3.2}, " f"{zoom_speed_str}")
def mouse(event, x, y, flags, param): global hsv hue = hsv[y, x, 0] lower = (hue, 30, 30) upper = (hue + 5, 250, 250) print(hsv.dtype, hsv.shape) mask = cv.inRange(hsv, lower, upper) # TypeError: Expected Ptr<cv::UMat> for argument '%s' img2 = cv.bitwise_and(img, img, mask=mask) cv.imshow('window', np.hstack([img, img2])) cv.displayStatusBar('window', f'hue={hue}')
def key(self, k): """Handle key events and send them to the current object.""" text = 'key {} ({})'.format(k, ord(k)) cv.displayStatusBar(self.win, text, 1000) if k in self.shortcuts: self.shortcuts[k]() self.draw() return True elif self.node != None: self.node.key(k) self.draw() return True return False
def mouseEvent(self, event, x, y, flag, param): if self.brushed == True: if event == cv2.EVENT_LBUTTONDOWN: self.pressed = True cv2.circle(self.layer_back, (x, y), self.circle_radius, self.brush_color, -1) # 实心圆 if event == cv2.EVENT_MOUSEMOVE and self.pressed: cv2.circle(self.layer_back, (x, y), self.circle_radius, self.brush_color, -1) # 实心圆 if event == cv2.EVENT_LBUTTONUP: self.pressed = False if event == cv2.EVENT_MOUSEMOVE and self.pressed == False: # 临时显示画笔层 cv2.circle(self.layer_tmp, (self.last_x, self.last_y), self.circle_radius, self.erase_color, -1) # 每执行一步这个操作,imgsMerge、imshow就会立马执行,因此之前的消去不会起作用 cv2.circle(self.layer_tmp, (x, y), self.circle_radius, self.brush_color, -1) self.last_x = x self.last_y = y elif self.erased == True: if event == cv2.EVENT_LBUTTONDOWN: self.pressed = True cv2.circle(self.layer_back, (x, y), self.circle_radius, self.erase_color, -1) elif event == cv2.EVENT_MOUSEMOVE and self.pressed == True: cv2.circle(self.layer_back, (x, y), self.circle_radius, self.erase_color, -1) elif event == cv2.EVENT_LBUTTONUP: self.pressed = False elif self.seed == True: if event == cv2.EVENT_LBUTTONUP: result = floodfill_with_gap(self.layer_show, y, x, 10) cv2.imwrite(self.save_path, result) cv2.displayStatusBar(self.win_name, "Result has been saved!")
def _update(self): """Updates an image in the already drawn window.""" viz = self.img.copy() contours = _find_exterior_contours(self.mask) viz = cv.drawContours(viz, contours, -1, color=(255, ) * 3, thickness=-1) viz = cv.addWeighted(self.img, 0.75, viz, 0.25, 0) viz = cv.drawContours(viz, contours, -1, color=(255, ) * 3, thickness=1) self.mean, self.stddev = cv.meanStdDev(self.img, mask=self.mask) meanstr = "mean=({:.2f}, {:.2f}, {:.2f})".format(*self.mean[:, 0]) stdstr = "std=({:.2f}, {:.2f}, {:.2f})".format(*self.stddev[:, 0]) cv.imshow(self.name, viz) cv.displayStatusBar(self.name, ", ".join((meanstr, stdstr)))
def mouse(self, event, x, y, flags, param): """Mouse callback.""" text = '{} in ({}, {}) flags={}, param={}'.format( event, x, y, flags, param) cv.displayStatusBar(self.win, text, 1000) if event == cv.EVENT_LBUTTONDOWN: # draw_selection objects under mouse click self.select_obj_at(event, x, y, flags, param) App.win = self self.p0 = x, y self.p1 = x, y self.text = 'p0 = ({}, {})'.format(x, y) cv.displayStatusBar(self.win, self.text, 2000) cv.displayOverlay(self.win, self.text, 1000) # draw rectangle if ALT key is pressed if flags == cv.EVENT_FLAG_ALTKEY: rect = Rectangle(self.img, (x, y), (x, y), RED, 3) self.objects.append(Rectangle(rect)) if flags == cv.EVENT_FLAG_SHIFTKEY: self.pos0 = x, y elif event == cv.EVENT_MOUSEMOVE: if flags == cv.EVENT_FLAG_ALTKEY: print('ALT') self.objects[-1].set_p1(x, y) elif flags == cv.EVENT_FLAG_CTRLKEY: print('CTRL KEY') elif flags == cv.EVENT_FLAG_SHIFTKEY: self.obj.pos = x, y elif event == cv.EVENT_LBUTTONUP: cv.displayOverlay(self.win, 'Mouse released', 1000) self.draw()
def onMouseCheckIslands(self, event, x, y, flags, param): #ss = param img = self.image().copy() if not hasattr(self.onMouseCheckSubIslands, "ml"): ml = ANN() if ( event == cv2.EVENT_LBUTTONDOWN ): island = self.getIslandWithPoint((y,x)) if island!=None and not island.isEmpty(): lum = img[y,x] area = island.area() shadeNum = self.getIndexOfShade(island.shade()) nnResult = max(island.nn_results()[0]) img = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) for value in island.coordinates().values(): col = value[1] row = value[0] img[row,col] = (0,255,0) shade_shape = island.shape_name() + "_s" + str(shadeNum) text = "({},{}) | Lum: {} | Area: {} | ShadeShape: {} | NN: {}".format(x,y,lum,area,shade_shape,nnResult) cv2.displayStatusBar(self.winName,text) nnResults = island.nn_results() textScore = "[{:.5f}, {:.5f}, {:.5f}, {:.5f}, {:.5f}]".format(nnResults[0,0],nnResults[0,1],nnResults[0,2],nnResults[0,3],nnResults[0,4]) textScore2 = "{:.5f}".format(island.nn_score_2()) cv2.namedWindow(self.winName2, cv2.WINDOW_NORMAL) cv2.displayStatusBar(self.winName2,textScore) cv2.imshow(self.winName2,island.image()) cv2.namedWindow(self.winName3, cv2.WINDOW_NORMAL) cv2.displayStatusBar(self.winName3,textScore2) cv2.imshow(self.winName3,island.nn_image()) if(event == cv2.EVENT_LBUTTONUP): img = self.image().copy() cv2.imshow(self.winName,img)
def draw_rectangle1(event, x, y, flags, param): global cord_list1_len if event == cv2.EVENT_LBUTTONDBLCLK: if cord_list1_len % 3 == 0: cv2.rectangle(img1, (x, y), (x + region, y + region), (255, 0, 0), 1) elif cord_list1_len % 3 == 1: cv2.rectangle(img1, (x, y), (x + region, y + region), (0, 255, 0), 1) else: cv2.rectangle(img1, (x, y), (x + region, y + region), (0, 0, 255), 1) img1_cord.append([x, y]) # print(img1[y, x]) # print(x, y) cord_list1_len += 1 print("##### img1 click " + str(cord_list1_len)) if cord_list1_len % total_click_sqrt == 0: print("-----[ Complete 1 ]-----") click_value.set(str(cord_list1_len)) cv2.displayStatusBar('image1', str(cord_list1_len))
def main(src=None): import sys src = 0 if src is None else src if len(sys.argv) > 1: src = sys.argv[1] getter = ImagesGetter(src, cam_warmup=0) WIN_NAME = 'press q to quit' cv2.namedWindow(WIN_NAME, cv2.WINDOW_NORMAL) for i, img in enumerate(getter): if img is None: print(i, ' - None to show') break print(i, end='\r') cv2.imshow(WIN_NAME, img) pressed = cv2.waitKey(1) if pressed == ord('q'): break elif pressed == ord('s'): path = "IMG_"+datetime.now().strftime("%Y%m%d-%H%M%S")+'.jpg' cv2.imwrite(path, img) cv2.displayStatusBar(WIN_NAME, 'Save photo to:\n'+path, 3000)
def mouse(self, event, x, y, flags, param): pos = np.array((x, y)) text = 'mouse event {} at {} with flags {}'.format(event, pos, flags) cv.displayStatusBar(self.win, text, 1000) if event == cv.EVENT_LBUTTONDOWN: App.win = self if flags & cv.EVENT_FLAG_SHIFTKEY: self.new(pos=(x, y)) else: self.select_node(pos) if event == cv.EVENT_MOUSEMOVE: if flags == cv.EVENT_FLAG_ALTKEY and self.node != None: self.node.pos = pos if self.node != None: self.node.mouse(event, pos, flags, param) self.draw()
def run_through_socket(model): try: print('receiving from Sher') while True: data, address = sock.recvfrom(SOCKET_BUFFER_SIZE) left = data[0:FRAME_SIZE] left = np.array(list(left)) left = left.reshape((100, 55, 3)) left = left.astype(uint8) center = data[FRAME_SIZE:FRAME_SIZE + FRAME_SIZE] center = np.array(list(center)) center = center.reshape((100, 55, 3)) center = center.astype(uint8) right = data[FRAME_SIZE + FRAME_SIZE:] right = np.array(list(right)) right = right.reshape((100, 55, 3)) right = right.astype(uint8) inp = np.array([left, center, right]) assert model is not None now = time.time() predictions = predict_image(model, inp, many=True) l_max = predictions[0].argmax() c_max = predictions[1].argmax() r_max = predictions[2].argmax() data = bytes('{}{}{}'.format(l_max, c_max, r_max).encode('ascii')) # predictions = [list(map(lambda v: '{0:.2f}'.format(v),p)) for p in predictions] then = time.time() print('spent time: {}'.format(then - now)) cv.imshow('left', left) cv.displayStatusBar( 'left', '{} {}'.format(classifiers[predictions[0].argmax()], predictions[0][predictions[0].argmax()])) cv.imshow('right', right) cv.displayStatusBar( 'right', '{} {}'.format(classifiers[predictions[2].argmax()], predictions[2][predictions[2].argmax()])) cv.imshow('center', center) cv.displayStatusBar( 'center', '{} {}'.format(classifiers[predictions[1].argmax()], predictions[1][predictions[1].argmax()])) cv.waitKey(15) sock.sendto(data, address) finally: if CONNECT_TO_SOCKET: print('closing socket') sock.close()
alternative = True if time() - t > time_interval: with condition: condition.notify() t = time() frame_to_show = np.copy(frame) frame_to_show = cv.rectangle(frame_to_show, hand_position[0], hand_position[1], (0, 255, 0), 5) frame_to_show = finder.place_marker(frame_to_show, hand_position[0], (0, 255, 0)) frame_to_show = finder.place_marker(frame_to_show, hand_position[1], (0, 255, 0)) frame_to_show = finder.place_marker(frame_to_show) cv.displayStatusBar('frame', "to get help press 'h'") text_position = (hand_position[0][0] + 20, hand_position[0][1] - 20) cv.addText(frame_to_show, classes[prediction], text_position, nameFont="Times", pointSize=30, color=(0, 255, 255)) loadingcat[prediction] = 1 show_cats(loadingcat) if debug: cv.imshow("masks_merged", masks_merged) cv.imshow("skin_mask", finder.skin_mask) cv.imshow("foreground_mask", finder.foreground_mask)
pass if __name__ == '__main__': import sys wname = 'TAR Project' fname = 'opencv.png' im = cv.imread(cv.samples.findFile(fname)) if im is None: print('Failed to load image file:', fname) sys.exit(1) cv.imshow(wname, im) cv.displayOverlay( wname, 'Cliquez sur un bouton pour interagir avec l\'application.', 0) cv.displayStatusBar(wname, 'On peut placer des informations et trackbars ici.', 0) cv.createTrackbar("Trackbar exemple", wname, 128, 255, callback_trackbar) cv.createTrackbar("Trackbar exemple", "", 128, 255, callback_trackbar) cv.createButton("Bouton", callback_button, wname, 0) while True: k = cv.waitKey(0) if k == 27: print('ESC') cv.destroyAllWindows() break cv.destroyAllWindows()
def toggle_shift(self): self.shift = not self.shift if self.shift: cv.displayStatusBar(self.win, 'SHIFT is ON', 1000) else: cv.displayStatusBar(self.win, 'SHIFT is OFF', 1000)
# -*- coding: utf-8 -*- # @Time : 2019/2/24 19:06 # @Author : Aries # @Site : # @File : Opencv_Getting_Start.py # @Software: PyCharm import numpy as np import cv2 img = cv2.imread('blocks-col.png', 0) cv2.imshow('image',img) k = cv2.waitKey(0) & 0xFF if k == 27: cv2.destroyAllWindows() elif k == ord('s'): cv2.imwrite('CopyOne.png', img) cv2.displayStatusBar()
def __call__(self): while True: contour = np.array(self.draw_points).reshape( (-1, 1, 2)).astype(np.int32) x, y, w, h = cv.boundingRect(contour) area = cv.contourArea(contour) if not self.current_printed and len( self.draw_points) > 4 and not self.drawing: self.export_images(contour) img = self.get_region_selection(contour) img = np.array(img) immune_cells, mask, _ = self.detector.get_immune_cells(img) inside_cells = [] for cell in immune_cells: moment = cv.moments(cell) center_x = int(moment['m10'] / moment['m00']) + x center_y = int(moment['m01'] / moment['m00']) + y if cv.pointPolygonTest(contour, (center_x, center_y), False) >= 0: inside_cells.append(cell) immune_cells = inside_cells if not self.current_printed: self.current_immune_cells = len(immune_cells) print("Immune cells in selection: {}".format( len(immune_cells))) self.current_printed = True img = cv.cvtColor(img, cv.COLOR_RGB2BGR) cvimg2 = img.copy() cvimg2 = cv.drawContours(cvimg2, immune_cells, -1, (0, 255, 0)) updated_list = [[p[0] - x, p[1] - y] for p in self.draw_points] updated_contour = np.array(updated_list).reshape( (-1, 1, 2)).astype(np.int32) cv.drawContours(cvimg2, [updated_contour], 0, (255, 255, 255), 4) if self.conf.options.advanced: cv.imshow(self.mask_window, mask) cv.imshow(self.original_window, img) cv.imshow(self.immunocells_window, cvimg2) over = self.draw_overview_overlay() cv.imshow(self.overview_window, over) if area > 0: cv.displayStatusBar( self.overview_window, "Immune cells in selection: {}, immune cells per square millimeter: {}" .format( self.current_immune_cells, self.current_immune_cells / (area / self.pixels_per_square_mm))) key = cv.waitKeyEx(100) if key == KEY_ESC: return elif key == KEY_SPACE: if self.drawing: self.current_printed = False self.update_overview = True print("Stopped drawing") self.drawing = False self.overview = self.original_overview.copy() else: print("Started drawing") self.drawing = True self.draw_points = [] self.overview_draw_points = [] self.selected_regions = [] elif key != -1: print("Button pressed {}".format(key))
class Render: np.set_printoptions(threshold=sys.maxsize) video = cv2.VideoCapture('test.mp4') prevFrame = None DTWMemory = "float" prevNum = -1 distance = None p1 = Process(target=PostData, args=(distance, )) DTWArray = np.array([[1, 2], [1, 1]]) print("video is created") if not video.isOpened(): print("Error openincg video stream or file") ##cv2.displayStatusBar("Video", "this is mh test", 25) while video.isOpened(): # Capture frame-by-frame ret, frame = video.read() grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) pixelArray = getArray(grayFrame, 260, 300, 250, 300) # pixelArray = np.hstack(grayFrame[222, :, 362]) if prevNum == 1: DTWArray, distance = DTW.DTWDistance(prevFrame, pixelArray) prevNum = 0 # print(DTWArray) # print('space') # PostData(2342143245) p1 = Process(target=PostData, args=(distance, )) p1.start() # DTW.plotG(prevFrame, pixelArray, DTWArray) else: prevNum = 1 prevFrame = pixelArray cv2.putText(grayFrame, str(DTW.averagePointDifference(DTWArray)), (50, 400), cv2.FONT_HERSHEY_SIMPLEX, 1, (124, 252, 0), 2) if ret: # cv2.putText(grayFrame, str(distance), (50, 400), cv2.FONT_HERSHEY_SIMPLEX, 2, (124, 252, 0), 2) cv2.rectangle(grayFrame, (222, 350), (362, 250), (124, 252, 0), 2) # cv2.rectangle(grayFrame, (300, 350), (320, 250), (124, 252, 0), 2) cv2.rectangle(grayFrame, (260, 350), (300, 250), (124, 252, 0), 2) ##TrackLine.TrackLines(grayFrame, getArray(grayFrame, 222, 362, 250, 350)) cv2.imshow('Video Gray', grayFrame) cv2.displayStatusBar("Video", "this is mh test", 25) fps = int(video.get(5)) if cv2.waitKey(20) & 0xFF == ord('c'): break else: break # When everything done, release the video capture object print("Video closed") video.release() # Closes all the frames cv2.destroyAllWindows()
def status(self, msg): cv.displayStatusBar(self.win, msg, 1000)
# by nngogol import numpy as np, cv2 as cv cv2 = cv # # press Q, E, A, R, 1, 2, 3, 4 # # Name your window root_wind = 'main' cv.namedWindow(root_wind) ms_delay = 1500 mbox_up = lambda text: cv.displayOverlay(root_wind, text, ms_delay) mbox_bottom = lambda text: cv.displayStatusBar(root_wind, text, ms_delay) # Create a black image img = np.ones((512, 512, 3), np.uint8) while True: cv.imshow(root_wind, img) # keyboard events code = cv.waitKey(1) if code == ord('q'): break if code == ord('a'): mbox_up('hello') # change colors: if code == ord('e'):
def menggaris(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: daftar_garis.append([y, x]) print(f'[I] Start point {[y,x]} saved.') elif event == cv2.EVENT_LBUTTONUP: daftar_garis[-1] += [y, x] print(f'[I] End point {[y,x]} saved.') elif event == cv2.EVENT_RBUTTONDOWN: print(f'[I] Line {daftar_garis.pop()} erased.') # creates window and callback cv2.namedWindow(judul) cv2.setMouseCallback(judul, menggaris) cv2.imshow(judul, im_back) cv2.displayStatusBar( judul, 'Every node is a line. Create line by drag from one point to another.') cv2.waitKey() cv2.destroyAllWindows() # calculations peta = {'titik': [], 'jalur': [[]]} for i, garis in enumerate(daftar_garis): ya, xa, yb, xb = garis yc = (ya + yb) // 2 xc = (xa + xb) // 2 s = np.sqrt((ya - yb)**2 + (xa - xb)**2) s = int(s) peta['titik'].append([yc, xc, s]) peta['jalur'][0].append(i) # you can add route manually