if event == cv2.EVENT_LBUTTONDOWN: mouse_pressed = True x, y = _x, _y show_img = np.copy(img) elif event == cv2.EVENT_MOUSEMOVE: if mouse_pressed: show_img = np.copy(img) cv2.rectangle(show_img, (x, y), (_x, _y), (0, 255, 0), 3) elif event == cv2.EVENT_LBUTTONUP: mouse_pressed = False w, h = _x - x, _y - y cv2.namedWindow('image') cv2.setMouseCallback('image', mouse_Callback) while True: cv2.imshow('image', show_img) k = cv2.waitKey(1) if k == ord('a') and not mouse_pressed: if w * h > 0: break cv2.destroyAllWindows() labels = np.full(img.shape[:2], cv2.GC_INIT_WITH_MASK, np.uint8) bgdModel = np.full(img.shape[:2], cv2.GC_PR_BGD, np.float64) fgdModel = np.full(img.shape[:2], cv2.GC_PR_FGD, np.float64) labels, bgdModel, fgdModel = cv2.grabCut(img, labels, (x, y, w, h), None, None,
if event == cv2.EVENT_LBUTTONDBLCLK: global b,g,r,xpos,ypos, clicked clicked = True xpos = x ypos = y b,g,r = img[y,x] b = int(b) g = int(g) r = int(r) if area <= 662000: cv2.namedWindow('image') else: cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.setMouseCallback('image', draw_function) while(1): cv2.imshow("image",img) if clicked: redEnd = (round(width * .735), round(height * .1)) textStart = (round(width * .85), round(height * .88)) #cv2.rectangle(image, startpoint, endpoint, color, thickness) -1 thickness fills rectangle entirely cv2.rectangle(img, (20,20), recEnd, (b,g,r), -1) #Creating text string to display ( Color name and RGB values ) text = getColorName(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b) #cv2.putText(img,text,start,font(0-7), fontScale, color, thickness, lineType, (optional bottomLeft bool) ) #For very light colours we will display text in black colour if r + g + b >= 600 : cv2.putText(img,text, textStart, cv2.FONT_HERSHEY_TRIPLEX, 1,(0,0,0),1,cv2.LINE_AA)
def setupUi(self, Form): cv2.namedWindow('image') cv2.setMouseCallback('image', on_mouse, self.img) Form.setObjectName("Form") Form.resize(855, 664) self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(230, 30, 89, 23)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(580, 30, 89, 23)) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(95, 90, 89, 23)) self.label_3.setObjectName("label_3") self.label_4 = QtWidgets.QLabel(Form) self.label_4.setGeometry(QtCore.QRect(77, 180, 89, 23)) self.label_4.setObjectName("label_4") self.label_5 = QtWidgets.QLabel(Form) self.label_5.setGeometry(QtCore.QRect(90, 270, 89, 23)) self.label_5.setObjectName("label_5") self.label_6 = QtWidgets.QLabel(Form) self.label_6.setGeometry(QtCore.QRect(570, 360, 89, 23)) self.label_6.setObjectName("label_6") self.label_7 = QtWidgets.QLabel(Form) self.label_7.setGeometry(QtCore.QRect(220, 360, 89, 23)) self.label_7.setObjectName("label_7") self.line = QtWidgets.QFrame(Form) self.line.setGeometry(QtCore.QRect(50, 330, 741, 20)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.lineEdit = QtWidgets.QLineEdit(Form) self.lineEdit.setGeometry(QtCore.QRect(190, 80, 121, 41)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(Form) self.lineEdit_2.setGeometry(QtCore.QRect(190, 170, 121, 41)) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit_3 = QtWidgets.QLineEdit(Form) self.lineEdit_3.setGeometry(QtCore.QRect(190, 260, 121, 41)) self.lineEdit_3.setObjectName("lineEdit_3") self.lineEdit_4 = QtWidgets.QLineEdit(Form) self.lineEdit_4.setGeometry(QtCore.QRect(540, 80, 121, 41)) self.lineEdit_4.setObjectName("lineEdit_4") self.lineEdit_5 = QtWidgets.QLineEdit(Form) self.lineEdit_5.setGeometry(QtCore.QRect(540, 170, 121, 41)) self.lineEdit_5.setObjectName("lineEdit_5") self.lineEdit_6 = QtWidgets.QLineEdit(Form) self.lineEdit_6.setGeometry(QtCore.QRect(540, 260, 121, 41)) self.lineEdit_6.setObjectName("lineEdit_6") self.lineEdit_7 = QtWidgets.QLineEdit(Form) self.lineEdit_7.setGeometry(QtCore.QRect(190, 410, 121, 41)) self.lineEdit_7.setObjectName("lineEdit_7") self.lineEdit_8 = QtWidgets.QLineEdit(Form) self.lineEdit_8.setGeometry(QtCore.QRect(190, 500, 121, 41)) self.lineEdit_8.setObjectName("lineEdit_8") self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(700, 270, 126, 33)) self.pushButton.setObjectName("pushButton") self.lineEdit_9 = QtWidgets.QLineEdit(Form) self.lineEdit_9.setGeometry(QtCore.QRect(190, 590, 121, 41)) self.lineEdit_9.setObjectName("lineEdit_9") self.lineEdit_10 = QtWidgets.QLineEdit(Form) self.lineEdit_10.setGeometry(QtCore.QRect(540, 410, 121, 41)) self.lineEdit_10.setObjectName("lineEdit_10") self.lineEdit_11 = QtWidgets.QLineEdit(Form) self.lineEdit_11.setGeometry(QtCore.QRect(540, 500, 121, 41)) self.lineEdit_11.setObjectName("lineEdit_11") self.lineEdit_12 = QtWidgets.QLineEdit(Form) self.lineEdit_12.setGeometry(QtCore.QRect(540, 590, 121, 41)) self.lineEdit_12.setObjectName("lineEdit_12") self.label_8 = QtWidgets.QLabel(Form) self.label_8.setGeometry(QtCore.QRect(90, 420, 51, 23)) self.label_8.setObjectName("label_8") self.label_10 = QtWidgets.QLabel(Form) self.label_10.setGeometry(QtCore.QRect(30, 600, 131, 23)) self.label_10.setObjectName("label_10") self.label_9 = QtWidgets.QLabel(Form) self.label_9.setGeometry(QtCore.QRect(90, 510, 51, 23)) self.label_9.setObjectName("label_9") self.label_11 = QtWidgets.QLabel(Form) self.label_11.setGeometry(QtCore.QRect(460, 598, 51, 23)) self.label_11.setObjectName("label_11") self.label_12 = QtWidgets.QLabel(Form) self.label_12.setGeometry(QtCore.QRect(430, 420, 71, 23)) self.label_12.setObjectName("label_12") self.label_13 = QtWidgets.QLabel(Form) self.label_13.setGeometry(QtCore.QRect(430, 510, 71, 23)) self.label_13.setObjectName("label_13") self.pushButton_2 = QtWidgets.QPushButton(Form) self.pushButton_2.setGeometry(QtCore.QRect(700, 600, 126, 33)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton.clicked.connect(self.setting) self.pushButton_2.clicked.connect(self.setting_2) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) cv2.imshow('image', self.img)
begin=True return cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1000) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 700) init=True cv2.namedWindow("Tracking") cv2.createTrackbar("dp", "Tracking", 50, 100, nothing) cv2.createTrackbar("param1", "Tracking", 20, 200, nothing) cv2.createTrackbar("param2", "Tracking", 30, 200, nothing) cv2.createTrackbar("minRadius", "Tracking", 13, 200, nothing) cv2.createTrackbar("maxRadius", "Tracking", 90, 200, nothing) cv2.namedWindow("output") cv2.setMouseCallback("output", mouse_drawing) R=[] def get_angle_and_pos(x1,x2,y1,y2): d=np.sqrt(np.power(x1-x2,2)+np.power(y1-y2,2)) angle=np.arctan2(y1-y2,x1-x2) xs = x1 - np.cos(angle)*d/2 ys = y1 - np.sin(angle)*d/2 return xs,ys,angle while True: # def get_measurements(): l_h = cv2.getTrackbarPos("LH", "Tracking") dp=cv2.getTrackbarPos("dp", "Tracking") param1=cv2.getTrackbarPos("param1", "Tracking")
# Events = [i for i in dir(cv2) if 'EVENT' in i] # print(Events) def Mouse_Event(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: text_XY = str(x) + ", " + str(y) font = cv2.FONT_ITALIC color = (255, 0, 0) cv2.putText(IMG, text_XY, (x, y), font, 0.5, color, 1, cv2.LINE_AA) cv2.imshow("Frame", IMG) if event == cv2.EVENT_RBUTTONDOWN: blue = IMG[y, x, 0] green = IMG[y, x, 1] red = IMG[y, x, 2] text_BGR = str(blue) + ", " + str(green) + ", " + str(red) font = cv2.FONT_HERSHEY_DUPLEX color = (200, 200, 200) cv2.putText(IMG, text_BGR, (x, y), font, 0.5, color, 1, cv2.LINE_8) cv2.imshow("Frame", IMG) IMG = np.zeros((512, 512, 3), np.uint8) # IMG = cv2.imread("D:\opencv-master\samples\data\opencv-logo-white.png", 1) cv2.imshow("Frame", IMG) cv2.setMouseCallback("Frame", Mouse_Event) cv2.waitKey(0) cv2.destroyAllWindows()
from cv2 import cv2 import pyperclip if len(sys.argv) == 1: picture = 'Just Slide.png' else: picture = sys.argv[1] img = cv2.imread(picture) def rgb_to_hex(rgb): return '%02x%02x%02x' % rgb # Converts RGB to Hex. RGB is passed as a tuple. def click_event(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: blue = img[y, x, 0] green = img[y, x, 1] red = img[y, x, 2] font = cv2.FONT_HERSHEY_SIMPLEX strXY = '#' + str(rgb_to_hex((red, blue, green))) pyperclip.copy(strXY) cv2.putText(img, strXY, (x, y), font, 1, (0, 0, 0), 2) cv2.imshow(picture, img) cv2.imshow(picture, img) cv2.setMouseCallback(picture, click_event) cv2.waitKey(0) cv2.destroyAllWindows()
captura.release() #dispensa o uso da webcam cv2.destroyAllWindows() return frame #ultimo frame capturado img = Camera() pontos = [] #img = cv2.imread("imagem/calibracao_2_17_01.jpg") #caso queira testar com uma imagem ao inves da câmera img = cv2.resize(img, (639, 479), interpolation=cv2.INTER_AREA) print( "selecione as 4 extremidades da imagem\nseguindo a ordem do exemplo abaixo\n ##########\n # 1 2 #\n # 4 3 #\n ##########" ) cv2.namedWindow('image') cv2.setMouseCallback('image', draw_circle) #habilita a função draw_circle while 1: #garante q haverá 4 pontos cv2.imshow('image', img) if cv2.waitKey(20) & 0xFF == 27: break if len(pontos) == 4: break cv2.destroyAllWindows() rows, cols, ch = img.shape pts1 = np.float32([pontos[0], pontos[1], pontos[3], pontos[2]]) ##pts2 deve seguir a propporção do retangulo base densenhado pelo braço ## o retangulo já esta pre-desenhado em .cod na memoria do braço
'''getting data from cursor''' if event == cv.EVENT_LBUTTONDOWN: # when left button is clicked print("({},{})".format(x, y)) font = cv.FONT_HERSHEY_SIMPLEX # font type cordinate = str(x) + ', ' + str(y) # making text cv.putText(img, cordinate, (x, y), font, .5, (255, 255, 0), 2) # putting text cv.imshow('image', img) # showing elif event == cv.EVENT_RBUTTONDOWN: #when right button is clicked blue = img[y, x, 0] # blue color dg green = img[y, x, 1] # green color dg red = img[y, x, 2] # red color dg font = cv.FONT_HERSHEY_COMPLEX #font type bgr_colors = str(blue) + ', ' + str(green)\ + ', ' + str(red) # making text cv.putText(img, bgr_colors, (x, y), font, .5, (0, 255, 255), 2) # putting text cv.imshow('image', img) # showing # img = numpy.zeros((512, 512, 3), numpy.uint8) img = cv.imread('imgs/lena.jpg') # setting up image url cv.imshow("image", img) # showing cv.setMouseCallback("image", click) # mouse callback function cv.waitKey(0) cv.destroyWindow(img) # destroying only img window(frame)
img_path = args.image_path img = cv2.imread(img_path, cv2.IMREAD_COLOR) img_copy = img.copy() img_to_cut = img.copy() while True: if video: _, img = cam.read() img_to_cut = img.copy() cv2.imshow('image', img) key = cv2.waitKey(100) if key == 115: # 's' cv2.namedWindow('select points') cv2.setMouseCallback('select points', get_mouse_points) selecting_points = True if selecting_points: if get_frame and video: img_copy = img.copy() get_frame = False cv2.imshow('select points', img_copy) if key == 99 and len(all_points) > 2 and selecting_points: # 'c' selected_points = True selecting_points = False cv2.setMouseCallback( 'select points', lambda event, x, y, flags, param: None) if selected_points:
def image_grid(index, x_offset=0, y_offset=0, i=0): cap.set(1, index) recalculate_window_stuff() # Resetting large image/grid to black each time. l_img = np.zeros((grid.window_height, grid.window_width, 3), np.uint8) cv2.imshow('image_selector_from_video', l_img) cv2.waitKey(1) index_for_frame_list = index while i < grid.number_of_cells: mouse_click.enable_draw_on_grid = False while cap.isOpened(): # Capture frame-by-frame ret, frame = cap.read() if ret: # Resize image s_image = cv2.resize(frame, (0, 0), None, grid.image_resize_x, grid.image_resize_y) # Put small images onto large image x_offset = (i % grid.number_of_columns) * int(grid.cell_width) y_offset = (i // grid.number_of_columns) * int(grid.cell_height) l_img[y_offset:y_offset + s_image.shape[0], x_offset:x_offset + s_image.shape[1]] = s_image # Show each small images drawn cv2.imshow('image_selector_from_video', l_img) cv2.waitKey(1) # i for count of images, index keeps track of where you are in frames i += 1 index += 1 if i == grid.number_of_cells or index == frames_in_video: mouse_click.enable_draw_on_grid = True # Parameters passed to mouse click function param = [l_img, index_for_frame_list] while True: cv2.setMouseCallback('image_selector_from_video', click_event, param) c = cv2.waitKey(1) if c == 27: # Escape print('Esc pressed to Exit') sys.exit() elif c == 32: # Space print('Spacebar pressed') # Getting rid of an uneven number of cells in lists if len(image_selection.cell_numbers_selection_temporary) % 2 == 0: pass else: image_selection.cell_numbers_selection_temporary.pop() if len(create_text_file.cell_numbers_list_for_each_grid) % 2 == 0: pass else: create_text_file.cell_numbers_list_for_each_grid.pop() # Clears lists for the case of single selected rectangle image_selection.cell_numbers_selection_temporary.clear() image_selection.image_list.clear() # Creates a image list from the temporary image lists of each grid of images. def create_permanent_image_list(): for images in image_selection.image_list_temporary: create_text_file.image_list_to_keep.append(images) create_permanent_image_list() # Transforms cell number in temporary grid into frame and appends to frame numbers list def each_grid_cells_into_frames_list(): for cell in create_text_file.cell_numbers_list_for_each_grid: frame_number = int(param[1]) + int(cell) create_text_file.frame_numbers_list.append(frame_number) each_grid_cells_into_frames_list() # Calculates frames spans backwards and forwards def make_list_of_frames_to_keep(image_count=0): # Putting into a list of two's for calculating frame spans frame_numbers_list_sliced = zip(create_text_file.frame_numbers_list[0::2], \ create_text_file.frame_numbers_list[1::2]) # Clear lists when space pressed create_text_file.list_of_frames_to_keep.clear() create_text_file.image_list_to_print.clear() for numbers in frame_numbers_list_sliced: # Forward frame spans if numbers[0] < numbers[1]: for frames1 in range(numbers[0], numbers[1] + 1): create_text_file.list_of_frames_to_keep.append(frames1) create_text_file.image_list_to_print.append(create_text_file. \ image_list_to_keep[image_count]) image_count += 1 # Backward frame spans elif numbers[0] > numbers[1]: for frames2 in range(numbers[1], numbers[0] + 1): create_text_file.list_of_frames_to_keep.append(frames2) create_text_file.image_list_to_print.append(create_text_file. \ image_list_to_keep[image_count]) image_count += 1 make_list_of_frames_to_keep() def bounding_box_cell_keys_to_frames(): # Changing the key of dict: cell numbers into frame numbers. temp_dict_to_append = {k + int(param[1]): v for (k, v) in bounding_box.\ temp_dict_and_cell_number_bboxes.items()} bounding_box.perm_dict_of_cell_num_and_bbox.update(temp_dict_to_append) bounding_box_cell_keys_to_frames() # Clear temp dict of bounding boxes ready for next lot of frames to have bounding boxes. bounding_box.temp_dict_and_cell_number_bboxes.clear() # Clearing temporary lists, so ready for the next lot of images. create_text_file.cell_numbers_list_for_each_grid.clear() image_selection.image_list_temporary.clear() def creates_text_file(): # Creating text file with frame numbers and what user tags images as. file = open('List_of_images.txt', 'w') for i, frame in enumerate(create_text_file.list_of_frames_to_keep): if frame in bounding_box.perm_dict_of_cell_num_and_bbox.keys(): file.write(f'{frame} {create_text_file.image_list_to_print[i]} \ {bounding_box.perm_dict_of_cell_num_and_bbox[frame]} \n') else: file.write(f'{frame} {create_text_file.image_list_to_print[i]} \n') file.close() # Output text file on each press of Space. creates_text_file() # Continue calling function if hasn't hit end of video if frames_in_video != index: return image_grid(index) # If Space bar pressed and end of the video exit out of loop and save tagging. elif (frames_in_video == index and index > grid.number_of_cells): creates_text_file() return
input_mask = os.path.join('', "", filename_mask) output_image = os.path.join('', "", filename_output) if filename_input is None: print('File input not exist.') exit() img = cv2.imread(filename_input) mask = np.zeros(img.shape, np.uint8) # handle_remove(input_image, output_image, input_mask, # mask, img) img_copy = img.copy() mask_copy = mask.copy() window_name = 'Draw mask. s:save; r: reset; q:quit' cv2.namedWindow(window_name) cv2.setMouseCallback(window_name, draw_circle) while True: cv2.imshow(window_name, img) k = cv2.waitKey(1) & 0xFF # cv2.imshow('mask', mask) if k == ord('r'): img = img_copy.copy() mask = mask_copy.copy() elif k == ord("s"): cv2.imwrite('mask.png', mask) print('[INFO]: processing') object_removal(input_image, output_image, input_mask) break elif k == ord("q"): cv2.destroyAllWindows() exit()
# converting images required in order to call getContour() imgCanny = cv2.Canny(mask, threshold1, threshold2) kernel = np.ones((5, 5)) imgDil = cv2.dilate(imgCanny, kernel, iterations=1) getContour(imgDil, img) while True: for i in range(counter): cv2.circle(img, (points[i][0], points[i][1]), 5, (0, 0, 255), cv2.FILLED) cv2.imshow('Image', img) if counter == 2: break cv2.setMouseCallback('Image', mousePoints) cv2.waitKey(1) dist = abs(points[0, 1] - points[1, 1]) print('Height Estimate: {:.2f}m'.format(dist / h)) addEstimate(img, '{:.2f}m'.format(dist / h)) cv2.imshow('Image', img) while not (cv2.waitKey(1) & 0xFF == ord('q')): pass cv2.destroyAllWindows()
def draw_function(event, x, y, flags, param): if event == cv2.EVENT_MOUSEMOVE: global b, g, r, xpos, ypos, moved moved = True xpos = x ypos = y b, g, r = img[ y, x] #BGR, since OpenCV represents images as NumPy arrays in reverse order b = int(b) g = int(g) r = int(r) cv2.namedWindow("colors_win") cv2.setMouseCallback("colors_win", draw_function) while (1): cv2.imshow("colors_win", img) if (moved): #text display config cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1) text = getName(r, g, b) + " R=" + str(r) + " G=" + str(g) + " B=" + str(b) cv2.putText(img, text, (50, 50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA) if (r + g + b >= 600):
REF_POINT = [(x, y)] print('mouse down', x, y) elif event == cv2.EVENT_LBUTTONUP: # record the ending (x, y) coordinates and indicate that # the cropping operation is finished REF_POINT.append((x, y)) RESULT_DICT[FIELD].append(REF_POINT) print('mouse up', x, y) # draw a rectangle around the region of interest cv2.rectangle(IMAGE, REF_POINT[0], REF_POINT[1], (0, 255, 0), 2) cv2.imshow("image", IMAGE) print(RESULT_DICT) cv2.namedWindow("image") cv2.setMouseCallback("image", getBBs) ############################################################################################################ # Sort Pics ############################################################################################################ BREED_COUNT = 0 IMAGE_COUNT = 0 BREED = BREEDS[BREED_COUNT] print('BREED:', BREED) print(len(PICS), '# of pics') PICS = pAnimals[pAnimals['breed'] == BREED].path.tolist() def loadIm(breed, randPic=False): # loads image from dataset
origin_img = img # 이미지 재처리 해서 화면에 띄운다. img, img_bin = convert_image(img) img_final_bin = edit_img(80, 1, 1, 1, 1, 1, 1, img_bin) dst = cv2.addWeighted(img, 0.4, img_final_bin, 0.6, 0) # 재처리된 이미지를 디비와 비교하여 같거나 비슷한 템플릿이 있는지 찾아 본다. # 찾아서 있다면 바로 아래 연산 건너뛴다. # 위 연산 결과가 없으면 이미지에 사용자 입력 받아서 쓴다. drawing = False mode = True ix, iy = -1, -1 cv2.namedWindow('image') cv2.setMouseCallback('image', draw_line) while True: cv2.imshow('image', dst) if cv2.waitKey(0) & 0xFF == 27: break # 이미지에서 사각형 찾이 라벨링 하고 최종 결과 출력 한다. img, img_bin = convert_image(dst) img_final_bin = edit_img(80, 1, 1, 1, 1, 1, 1, img_bin) contours, boundingBoxes = find_contours(img_final_bin, True) inx = 1 for var in contours: x, y, w, h = cv2.boundingRect(var) if h > 8 and w > 10: new_img = origin_img[y:y + h, x:x + w] img_final_result = cv2.drawContours(origin_img, var, -1, (0, 255, 0), 2)
drawing = False # true if mouse is pressed ix, iy = -1, -1 def draw_shape(event, x, y, flags, param): # mouse callback func global ix, iy, drawing if event == cv.EVENT_LBUTTONDOWN: drawing = True ix, iy = x, y elif event == cv.EVENT_MOUSEMOVE: if drawing == True: cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 0) elif event == cv.EVENT_LBUTTONUP: drawing = False cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 2) # if thickness -1 = fill cv.imshow("Image", img) img = np.zeros((512, 512, 3), np.uint8) while True: cv.namedWindow("Image", cv.WINDOW_NORMAL) cv.imshow("Image", img) cv.setMouseCallback("Image", draw_shape) cv.waitKey(0) cv.destroyAllWindows()
mouse_down = False elif event == cv2.EVENT_MOUSEMOVE: if mouse_down: cv2.line(draw, pt1=last_point, pt2=(x, y), color=circle_color, thickness=circle_radius) last_point = (x, y) draw = np.ones((512, 1024, 3), np.uint8) draw[:] = (255, 255, 255) cv2.namedWindow('Draw') cv2.setMouseCallback('Draw', Draw_Circle) while (True): cv2.imshow('Draw', draw) if cv2.waitKey(1) == ord('q'): break cv2.destroyAllWindows() #绘制的图像储存于draw中 #====================================== #垂直投影法对图像进行处理 picture = [] #得到的处理结果储存于picture列表中 GrayImage = cv2.cvtColor(draw, cv2.COLOR_BGR2GRAY) #转为灰度图 ret, thresh = cv2.threshold(GrayImage, 130, 255, cv2.THRESH_BINARY) #二值化处理 (thresh_h, thresh_w) = thresh.shape
b, g, r = get_color(x, y, params) hsv.set_trackbars(b, g, r) # make a resizable window window_name = 'Image' cv.namedWindow(window_name, cv.WINDOW_GUI_NORMAL) image_file = "/some/path/to/image.png" # <- path to local image here # create the window with the trackbars hsv = HSVTrackbars() hsv.tolerance = 5 while bool(cv.getWindowProperty(window_name, cv.WND_PROP_VISIBLE)): try: img = cv.imread(image_file) img = hsv.apply_hsv(img) # show the image cv.imshow(window_name, img) # click on the image to set the hsv values cv.setMouseCallback(window_name, on_click, img) if cv.waitKey(1) & 0xFF == ord("q"): break # if Q is pressed except KeyboardInterrupt: break # clean up cv.destroyAllWindows()
import numpy as np from cv2 import cv2 img = np.zeros((512, 512, 3), np.uint8) point = [] def click_event(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(img, (x, y), 5, (120, 200, 255), -1) point.append((x, y)) if len(point) >= 2: cv2.line(img, point[-1], point[-2], (255, 0, 0), 5) cv2.imshow('image', img) cv2.imshow('image', img) cv2.setMouseCallback('image', click_event) cv2.waitKey(0) cv2.destroyAllWindows()
refPt.append((x, y)) cropping = False cv.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2) cv.imshow("image", image) image = cv.imread('1.jpg') image = cv.resize(image, dsize=(0, 0), fx=0.2, fy=0.2, interpolation=cv.INTER_LINEAR) clone = image.copy() cv.namedWindow("image") cv.setMouseCallback("image", click_and_crop) while True: cv.imshow("image", image) key = cv.waitKey(1) & 0xFF if key == ord("r"): image = clone.copy() elif key == ord("c"): if len(refPt) == 2: roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]] print(refPt) cv.imshow("ROI", roi) cv.waitKey(0) elif key == ord("q"): cv.imwrite('roi.jpg', roi)
def draw_rectangle_on_key_press(squares, img): """This functions handles the drawing on rectangles on screen on keypress. It does so by taking the top left and bottom right points of the rectangle and drawing it onto image""" global image_to_show squares = [item for t in squares for item in t] image_to_show = np.copy(img) original_image = np.copy(img) finish = False i = -2 # skip_key = False while not finish: display_image('suDOku', image_to_show) # if not skip_key: key = cv2.waitKey(0) # right key if key == ord('d'): i += 2 if i % 18 == 0: i -= 18 elif key == ord('a'): i -= 2 if i % 18 == 16: i += 18 elif key == ord('s'): i += 18 if i >= 162: i -= 162 elif key == ord('w'): i -= 18 if i < 0: i += 162 elif key == ord('1') or key == ord('2') or key == ord( '3') or key == ord('4') or key == ord('5') or key == ord( '6') or key == ord('7') or key == ord('8') or key == ord( '9'): # cv2.setMouseCallback("moving rectangles", # detect_mouse_coordinates, (squares, img)) display_numbers_on_grid(i, key, squares, img, original_image) elif key == ord('u'): undo_operation(squares, img, original_image) elif key == ord('r'): redo_operation(squares, img, original_image) elif key == ord('m'): delete_operation(i, squares, img, original_image) elif key == 27: finish = True '''if mouse_coordinates[0] != -1 and mouse_coordinates[1] != -1: skip_key = True else: skip_key = False''' # mouse_coordinates = (-1, -1) # erasing previously drawn triangles by creating clone of image image_to_show = np.copy(img) top_left = (int((squares[i])[0]), int((squares[i])[1])) bottom_right = (int((squares[i + 1])[0]), int((squares[i + 1])[1])) def detect_mouse_coordinates(event, x, y, flags, param): # global image_to_show nonlocal i mouse_coordinates = (0, 0) squares = param[0] img = param[1] if event == cv2.EVENT_LBUTTONDOWN: mouse_coordinates = (x, y) # print("mouse", mouse_coordinates) for j in range(161): point = squares[j] next_point = squares[j + 1] if ((mouse_coordinates[0] > point[0] and mouse_coordinates[0] < next_point[0]) and (mouse_coordinates[1] > point[1] and mouse_coordinates[1] < next_point[1])): point = (int(point[0]), int(point[1])) next_point = (int(next_point[0]), int(next_point[1])) break for k in range(161): squares[k] = (int(squares[k][0]), int(squares[k][1])) squares[k + 1] = (int(squares[k + 1][0]), int(squares[k + 1][1])) if (squares[k] == point and squares[k + 1] == next_point): break i = k top_left = point bottom_right = next_point image_to_show = np.copy(img) cv2.rectangle(image_to_show, top_left, bottom_right, (0, 255, 0), 3) display_image('moving rectangles', image_to_show) cv2.setMouseCallback("moving rectangles", detect_mouse_coordinates, (squares, img)) cv2.rectangle(image_to_show, top_left, bottom_right, (0, 255, 0), 3) return
#creating RGB values of the pixel when we double click it def draw_function(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDBLCLK: global b, g, r, xpos, ypos, clicked clicked = True xpos = x ypos = y b, g, r = img[y, x] b = int(b) g = int(g) r = int(r) #setting up the actual mouse click cv2.setMouseCallback("Color Detection", draw_function) while (1): cv2.imshow("Color Detection", img) if (clicked): #cv2.rectangle(image, startpoint, endpoint, color, thickness)-1 fills entire rectangle cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1) #Creating text string to display( Color name and RGB values ) text = ("R = " + str(r) + ", G = " + str(g) + ", B = " + str(b)) #cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType ) cv2.putText(img, text, (50, 50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA)
def trace_ROI(App): global parameters, i, drawingROI, drawingCL, selectedLine, ROImask, ROI, cut_lines def updateSTrackbar(value): global i i = value return def initialize_mask(parameters): # global parameters # Compute the ROI mask once to keep it in memory roi_norm_str = eval(str(parameters['ROI'])) if roi_norm_str: roi_norm = np.asarray(roi_norm_str) roi = (roi_norm * [ parameters['Width_Image'], parameters['Height_Image'] ]).astype(int) # scale ROI with image size, round to nearest pixel roi_mask = np.zeros( (parameters['Height_Image'], parameters['Width_Image']), dtype=np.uint8) ROI_mask = cv2.drawContours(image=roi_mask, contours=[roi], contourIdx=0, color=(255, 255, 255), thickness=-1) else: roi = np.array([[0, 0]], dtype=np.int32) # ROI contour ROI_mask = np.ones( (parameters['Height_Image'], parameters['Width_Image']), dtype=np.uint8) return roi, ROI_mask def initialize_cut_line(parameters): # Builds the cut_lines array from the parameters # Cut line specified in the parameters file in normalized coordinates # (x1,y1), (x2,y2): read in, scale into image coordinates # Get all parameter fields that begin with 'cutLine cutline_keys = fnmatch.filter(parameters.keys(), 'Cut_Line*') cut_lines = [] for key in cutline_keys: cutLine_norm_str = eval(str(parameters[key])) if cutLine_norm_str: cutLine_norm = np.asarray(cutLine_norm_str) cutLine = (cutLine_norm * [ parameters['Width_Image'], parameters['Height_Image'] ]).astype( int ) # scale cut line with image size, round to nearest pixel else: cutLine = np.array([[0, 0]], dtype=np.int32) # default cut line cut_lines.append(cutLine) return cut_lines def selectLine(event, x, y, flags, params): global drawingROI, drawingCL, selectedLine, ROI, ROImask, cut_lines, parameters if mode == 'ROI': if drawingROI: ROI[-1] = [x, y] if event == cv2.EVENT_LBUTTONDOWN: # Left click if not drawingROI: ROI = np.array([[0, 0]], dtype=np.int32) ROI[-1] = [x, y] drawingROI = True ROI = np.append(ROI, [[x, y]], axis=0) if event == cv2.EVENT_RBUTTONDOWN: # Right click # print('ROI (absolu) : \n{}\n'.format([[couple[0],couple[1]] for couple in ROI])) ROI_rel = np.zeros_like(ROI, dtype=float) ROI_rel[:, 0] = np.around(ROI[:, 0] / parameters['Width_Image'], decimals=2) ROI_rel[:, 1] = np.around(ROI[:, 1] / parameters['Height_Image'], decimals=2) strInfo = 'ROI : {}'.format([[couple[0], couple[1]] for couple in ROI_rel]) print(strInfo + '\n') try: App.Info.set(strInfo) except: pass drawingROI = False ROImask = np.zeros( (parameters['Height_Image'], parameters['Width_Image']), dtype=np.uint8) cv2.drawContours(ROImask, [ROI], 0, (255, 255, 255), -1) parameters['ROI'] = str([[couple[0], couple[1]] for couple in ROI_rel]) # + '\n' if mode == 'CL': if drawingCL: cut_lines[selectedLine - 1][-1] = [x, y] if event == cv2.EVENT_LBUTTONDOWN: # Left click if not drawingCL: cut_lines[selectedLine - 1] = np.array([[0, 0]], dtype=np.int32) cut_lines[selectedLine - 1][-1] = [x, y] drawingCL = True cut_lines[selectedLine - 1] = np.append( cut_lines[selectedLine - 1], [[x, y]], axis=0) if event == cv2.EVENT_RBUTTONDOWN: # print('Ligne de coupe (absolu) : \n{}\n'.format([[couple[0],couple[1]] for couple in cut_line])) cut_lineRel = np.zeros_like(cut_lines[selectedLine - 1], dtype=float) cut_lineRel[:, 0] = np.around(cut_lines[selectedLine - 1][:, 0] / parameters['Width_Image'], decimals=2) cut_lineRel[:, 1] = np.around(cut_lines[selectedLine - 1][:, 1] / parameters['Height_Image'], decimals=2) strInfo = 'Ligne de coupe #{} : {}'.format( selectedLine, [[couple[0], couple[1]] for couple in cut_lineRel]) print(strInfo + '\n') try: App.Info.set(strInfo) except: pass drawingCL = False parameters['Cut_Line' + str(selectedLine)] = str( [[couple[0], couple[1]] for couple in cut_lineRel]) # + '\n' drawingROI = False # Tracé du ROI en cours drawingCL = False # Tracé de la Cut Line en cours selectedLine = 0 # CutLine selected mode = 'ROI' # 'ROI' ou 'CL' showHelp = True lineColors = [(0, 0, 255), (255, 0, 0), (0, 255, 0), (255, 0, 255)] # Red / Blue / Green / Violet parameters = App.parameters.copy() try: videoPath = App.VideoPath.get() excelPath = App.ExcelPath.get() except: videoPath = App.VideoPath excelPath = App.ExcelPath cap = cv2.VideoCapture(videoPath) time.sleep(0.5) if not cap.isOpened(): strInfo = 'Impossible d\'ouvrir : {}'.format(videoPath) print(strInfo) try: App.Info.set(strInfo) except: pass return tots = cap.get( cv2.CAP_PROP_FRAME_COUNT) # Set to a negative number for streaming parameters['Width_Image'] = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) parameters['Height_Image'] = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) cv2.namedWindow('Video Player', cv2.WINDOW_NORMAL) cv2.resizeWindow('Video Player', parameters['Width_Image'], parameters['Height_Image']) cv2.moveWindow('Video Player', 50, 50) if tots > 0: cv2.createTrackbar('S', 'Video Player', 0, int(tots) - 1, updateSTrackbar) cv2.setMouseCallback('Video Player', selectLine) status = 'play' isRunning = True i = 1 cut_lines = initialize_cut_line(parameters) ROI, ROImask = initialize_mask(parameters) # Reading loop while True: try: status = { ord(' '): 'play/pause', ord('r'): 'reset', 9: 'switch mode', # Tab 38: 'sel1', # & 49: 'sel1', # 1 233: 'sel2', # é 50: 'sel2', # 2 34: 'sel3', # " 51: 'sel3', # 3 39: 'sel4', # ' 52: 'sel4', # 4 ord('h'): 'switch help', -1: status, 27: 'exit' }[cv2.waitKey(1)] if (cv2.getWindowProperty('Video Player', 1) == -1) & (i > 1): # The user closed the window status = 'exit' if status == 'play': # mettre en bas ? i += 1 i %= tots if tots > 0: # The two next lines slow down the code a lot ! cap.set(cv2.CAP_PROP_POS_FRAMES, int(i)) cv2.setTrackbarPos('S', 'Video Player', int(i)) _, im = cap.read() overlay_ROI = im.copy() # for transparency if np.size(ROI) > 2: cv2.drawContours(overlay_ROI, [ROI], 0, (255, 255, 255), 2) if not drawingROI: overlay_ROI = cv2.bitwise_and(overlay_ROI, overlay_ROI, mask=ROImask) cv2.addWeighted(overlay_ROI, 0.2, im, 1 - 0.2, 0, im) overlay_CL = im.copy() # for transparency for ii, cut_line in enumerate(cut_lines): if np.size(cut_line) > 2: cv2.polylines(overlay_CL, [cut_line], 0, lineColors[ii], 3) cv2.addWeighted(overlay_CL, 0.8, im, 1 - 0.8, 0, im) if mode == 'ROI': txt = 'Selection du ROI' elif mode == 'CL': txt = 'Selection de la ligne de coupe #{}'.format(selectedLine) textdim, _ = cv2.getTextSize(txt, cv2.FONT_HERSHEY_DUPLEX, 0.5, 1) cv2.rectangle(im, (5 - 1, 20 + 2), (5 + textdim[0] + 1, 20 - textdim[1]), (255, 255, 255), -1) cv2.putText(im, txt, (5, 20), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) dy = 20 if showHelp: if mode == 'ROI': txt = 'r : remettre a zero le ROI' cv2.putText(im, txt, (5, parameters['Height_Image'] - 5 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) if not drawingROI: txt = 'clic gauche : selectionner le premier point du ROI' cv2.putText(im, txt, (5, parameters['Height_Image'] - 4 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) elif drawingROI: txt = 'clic gauche : selectionner le point suivant du ROI' cv2.putText(im, txt, (5, parameters['Height_Image'] - 4 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) txt = 'clic droit : selectionner le dernier point du ROI' cv2.putText(im, txt, (5, parameters['Height_Image'] - 3 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) txt = 'Tab : passer a la selection de la ligne de coupe' cv2.putText(im, txt, (5, parameters['Height_Image'] - 2 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) elif mode == 'CL': txt = '1-4 : selectionner la ligne de coupe #1-4' cv2.putText(im, txt, (5, parameters['Height_Image'] - 6 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) txt = 'r : remettre a zero la ligne de coupe #{}'.format( selectedLine) cv2.putText(im, txt, (5, parameters['Height_Image'] - 5 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) if not drawingCL: txt = 'clic gauche : selectionner le premier point de la ligne de coupe' cv2.putText(im, txt, (5, parameters['Height_Image'] - 4 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) elif drawingCL: txt = 'clic gauche : selectionner le point suivant de la ligne de coupe' cv2.putText(im, txt, (5, parameters['Height_Image'] - 4 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) txt = 'clic droit : selectionner le dernier point de la ligne de coupe' cv2.putText(im, txt, (5, parameters['Height_Image'] - 3 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) txt = 'Tab : passer a la selection du ROI' cv2.putText(im, txt, (5, parameters['Height_Image'] - 2 * dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) txt = 'Esc : quitter' cv2.putText(im, txt, (5, parameters['Height_Image'] - dy), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) txt = 'h : cacher l\'aide' cv2.putText(im, txt, (5, parameters['Height_Image'] - 1), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) else: txt = 'h : montrer l\'aide' cv2.putText(im, txt, (5, parameters['Height_Image'] - 1), cv2.FONT_HERSHEY_DUPLEX, 0.5, 1, 1) cv2.imshow('Video Player', im) if status == 'play': continue elif status == 'stay': i = int(cv2.getTrackbarPos('S', 'Video Player')) elif status == 'play/pause': status = 'stay' if isRunning else 'play' isRunning = not isRunning elif status == 'reset': if mode == 'ROI': parameters['ROI'] = None ROI, ROImask = initialize_mask(parameters) elif mode == 'CL': parameters['Cut_Line' + str(selectedLine)] = None cut_lines = initialize_cut_line(parameters) status = 'play' if isRunning else 'stay' elif status == 'switch mode': if mode == 'ROI': mode = 'CL' selectedLine = 1 else: mode = 'ROI' selectedLine = 0 status = 'play' if isRunning else 'stay' elif status == 'sel1': if not drawingCL: selectedLine = 1 mode = 'CL' status = 'play' if isRunning else 'stay' elif status == 'sel2': if not drawingCL: selectedLine = 2 mode = 'CL' status = 'play' if isRunning else 'stay' elif status == 'sel3': if not drawingCL: selectedLine = 3 mode = 'CL' status = 'play' if isRunning else 'stay' elif status == 'sel4': if not drawingCL: selectedLine = 4 mode = 'CL' status = 'play' if isRunning else 'stay' elif status == 'switch help': showHelp = not showHelp status = 'play' if isRunning else 'stay' elif status == 'exit': answer = messagebox.askquestion( message= 'Voulez vous enregistrer les modifications dans le fichier de paramètres ?', type='yesnocancel') if answer == 'cancel': status = 'play' if isRunning else 'stay' if answer == 'yes': App.parameters = parameters # Ecraser les anciens paramètres avec les nouveaux df = pandas.read_excel(excelPath, header=None) df.loc[App.comboBoxID.current() + 1, 9] = parameters['ROI'] for ii in range(1, 5): df.loc[App.comboBoxID.current() + 1, 9 + ii] = parameters['Cut_Line' + str(ii)] try: with pandas.ExcelWriter(excelPath) as writer: df.to_excel(writer, header=None, index=False, sheet_name='All') writer.save except PermissionError: messagebox.showerror( title='Erreur', message= 'Impossible d\'enregistrer les modifications, vérifier que le fichier n\'est pas utilisé par une autre application' ) status = 'play' if isRunning else 'stay' continue break if answer == 'no': break except KeyError as e: print("Invalid Key \"{:s}: {:d}\" was pressed".format( chr(e.args[0]), e.args[0])) cv2.destroyAllWindows() cap.release() return
ix, iy = -1, -1 # mouse callback function def draw_shape(event, x, y, flags, param): global ix, iy, drawing if event == cv.EVENT_LBUTTONDOWN: drawing = True ix, iy = x, y elif event == cv.EVENT_MOUSEMOVE: if drawing == True: cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 0) elif event == cv.EVENT_LBUTTONUP: drawing = False cv.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1) img = np.zeros((512, 512, 3), np.uint8) cv.namedWindow('image') cv.setMouseCallback('image', draw_shape) while (1): cv.imshow('image', img) if cv.waitKey(1) == ord('q'): break cv.destroyAllWindows()
def nothin(x): print(x) img = cv2.imread('image_2.jpg') img1 = cv2.resize(img, (960, 720)) print(img1.shape) #img = cv2.imread('yoda.png',0) #print(img.shape) img = np.zeros((720, 960, 3), np.uint8) output = cv2.addWeighted(img1, 0.1, img, 0.1, 0) cv2.namedWindow('window') cv2.setMouseCallback('window', mouse_drawing) cv2.createTrackbar('alpha', 'window', 0, 10, nothin) while (True): cv2.imshow('window', output) cv2.imshow('img', img) k = cv2.waitKey(1) & 0xFF if k == ord('m'): mode = not mode elif k == 27: break alpha = cv2.getTrackbarPos('alpha', 'window') * 0.1 beta = 1 - alpha output = cv2.addWeighted(img1, alpha, img, beta, 0)
if __name__ == "__main__": capture = cv2.VideoCapture("video/hockey.avi") is_destroy = False particle_list = [] if capture.isOpened(): while(True): ret,prev = capture.read() if ret == True: if is_cropped == False: firstFrame = copy.deepcopy(prev) the_firstFrame = copy.deepcopy(prev) image_w,image_h = prev.shape[1],prev.shape[0] while(is_cropped == False): cv2.namedWindow("choose_image",flags = 0) cv2.resizeWindow('choose_image', 1080, 800) cv2.setMouseCallback('choose_image', choose_frame) cv2.imshow('choose_image',firstFrame) cv2.waitKey(10)&0xff if is_destroy == False : cv2.destroyAllWindows() is_destroy = True particle_list = initial_particle() cv2.rectangle(prev, (int(ix - w * 0.5), int(iy - 0.5 * h)), (int(ix + w * 0.5), int(iy + 0.5 * h)), (0,255,0), 1) cv2.namedWindow('video', flags=0) cv2.resizeWindow('video', 1080, 800) cv2.imshow('video',prev) else: particle_list,prev = particlefilter(particle_list,copy.deepcopy(prev)) cv2.imshow('video',prev) else: break
import numpy as np from cv2 import cv2 as cv # função callback para tratar o mouse def draw_circle(event, x, y, flags, param): if event == cv.EVENT_LBUTTONDBLCLK: #se o usuário deu doubleclick com o botão esquerdo cv.circle(img, (x, y), 100, (255, 0, 0), -1) #desenha um círculo na posição do mouse #Criação de uma imagem preta, uma janela e definição da função callback do mouse para a janela criada img = np.zeros((512, 512, 3), np.uint8) cv.namedWindow('image') cv.setMouseCallback('image', draw_circle) while (1): cv.imshow('image', img) if cv.waitKey(20) & 0xFF == 27: break cv.destroyAllWindows()
x_inicial + 1:x_final - 1].mean(axis=0).mean(axis=0)) except RuntimeWarning as erro: print('Região Inválida! Erro: {}'.format((erro.__class__))) def desenharRetangulo(): global img, x_inicial, y_inicial, x_final, y_final if x_inicial != -1 and x_final != -1: cv2.rectangle(img, (x_inicial, y_inicial), (x_final, y_final), (0, 0, 255), 1) drawing = False # Verdadeiro quando o mouse está apertado, False caso contrário x_inicial, y_inicial, x_final, y_final = -1, -1, -1, -1 cv2.namedWindow('image') cv2.setMouseCallback('image', draw_rectangle) video = cv2.VideoCapture(0) video.set(3, 640) # definir largura para 640 (padrão é 640X480) video.set(4, 480) # definir altura para 480 (padrão é 640X480) video.set(5, 60) # tenta aumentar o fps, se possível while True: #ret, img = video.read() img = cv2.flip(video.read()[1], 1) desenharRetangulo() cv2.imshow("image", img) if cv2.waitKey(1) == 27: break video.release() cv2.destroyAllWindows()
import numpy as np from cv2 import cv2 img = np.zeros((512, 512, 3), np.uint8) cv2.namedWindow('Image') cv2.setMouseCallback('Image', )
global score, img, QB if event == cv2.EVENT_LBUTTONDOWN: if not QB[y][x].any() == 0: stp_x = y // img.shape[0] stp_y = x // img.shape[1] for a in range(1, img.shape[0]): for b in range(1, img.shape[1]): QB[stp_x * img.shape[0] + a][stp_y * img.shape[1] + b] = (0, 0, 0) score += 1 path = os.getcwd() img = cv2.imread(path + '\\QB.jpg') cv2.namedWindow('QB') cv2.setMouseCallback('QB', Q_B) while (1): QB = numpy.zeros((img.shape[0] * 3, img.shape[1] * 3 + 139, img.shape[2]), dtype=numpy.uint8) for a in range(0, 3): for b in range(0, 3): stp = random.randint(0, 1) if (stp): for c in range(0, img.shape[0]): for d in range(0, img.shape[1]): QB[a * img.shape[0] + c][b * img.shape[1] + d] = img[c][d] cv2.rectangle(QB, (b * img.shape[1], a * img.shape[0]), ((b + 1) * img.shape[1], (a + 1) * img.shape[0]), (187, 197, 57), 1) for a in range(0, 39):