def testLut(): testimg = cv2.imread('/Users/zjj/Desktop/IMG_3271.jpg') lutpath = '/Users/zjj/Desktop/lookup_0_origin_2.png' lut = MYLUT(lutpath) img = testimg.copy() img = lut.imageInLut(img) cv2.imwrite('/Users/zjj/Desktop/IMG_3271_lut.jpg', img) return 0 # testimg = cv2.imread('/Users/zjj/Downloads/照片/IMG_0495.JPG')\ # testimg = cv2.resize(testimg, (600, 400)) fileinlutdir = os.listdir('lut') fileinlutdir = sorted(fileinlutdir) for filename in fileinlutdir: if filename.endswith('.png') and filename.startswith('lookup'): lutpath = 'lut/' + filename print('Init', time.time()) lut = MYLUT(lutpath) img = testimg.copy() for i in range(1): print('Start', time.time()) img = lut.imageInLut(img) print('Finish', time.time()) windowname = filename + str(i) cv2.namedWindow(windowname, cv2.WINDOW_KEEPRATIO) cv2.resizeWindow(windowname, 1080, 1920) cv2.imshow(windowname, img) cv2.waitKey(0) cv2.destroyWindow(windowname) print("Done")
def detectColor(): def empty(a): pass cv2.namedWindow("TrackBars") cv2.resizeWindow("TrackBars", 640, 240) cv2.createTrackbar("Hue Min", "TrackBars", 0, 179, empty) cv2.createTrackbar("Sat Min", "TrackBars", 0, 255, empty) cv2.createTrackbar("Val Min", "TrackBars", 0, 255, empty) cv2.createTrackbar("Hue Max", "TrackBars", 179, 179, empty) cv2.createTrackbar("Sat Max", "TrackBars", 255, 255, empty) cv2.createTrackbar("Val Max", "TrackBars", 255, 255, empty) while True: img = cv2.imread("./lambo.jpeg") imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h_min = cv2.getTrackbarPos("Hue Min", "TrackBars") h_max = cv2.getTrackbarPos("Hue Max", "TrackBars") s_min = cv2.getTrackbarPos("Sat Min", "TrackBars") s_max = cv2.getTrackbarPos("Sat Max", "TrackBars") v_min = cv2.getTrackbarPos("Val Min", "TrackBars") v_max = cv2.getTrackbarPos("Val Max", "TrackBars") #print(v_min) # lower1 = np.array([h_min, s_min, v_min]) # upper1 = np.array([h_max, s_max, v_max]) lower = np.array([000, 000, 186]) upper = np.array([179, 255, 255]) mask = cv2.inRange(imgHSV, lower, upper) imgResult = cv2.bitwise_and(img, img, mask=mask) cv2.imshow("Original", img) cv2.imshow("HSV", imgHSV) cv2.imshow("Mask", mask) cv2.imshow("Result", imgResult) cv2.waitKey(0)
def displayIMG(img, windowName): cv2.namedWindow( windowName, cv2.WINDOW_NORMAL ) cv2.resizeWindow(windowName, 1000, 800) cv2.imshow(windowName, img)
def __init__(self, num, color=None): if color == 'white': # predefined values for mapping whites only init_h_min, init_h_max, init_s_min, init_s_max, init_v_min, init_v_max = 0, 179, 0, 59, 220, 255 init_thr1, init_thr2, init_area = 166, 171, 2000 elif color == 'green': init_h_min, init_h_max, init_s_min, init_s_max, init_v_min, init_v_max = 55, 90, 30, 170, 40, 245 init_thr1, init_thr2, init_area = 0, 255, 3000 else: init_h_min, init_h_max, init_s_min, init_s_max, init_v_min, init_v_max = 0, 179, 0, 255, 0, 255 init_thr1, init_thr2, init_area = 0, 255, 0 cv2.namedWindow(f"HSV_{num}") cv2.resizeWindow(f"HSV_{num}", 640, 240) cv2.createTrackbar(f"HUE Min_{num}", f"HSV_{num}", init_h_min, 179, empty) cv2.createTrackbar(f"HUE Max_{num}", f"HSV_{num}", init_h_max, 179, empty) cv2.createTrackbar(f"SAT Min_{num}", f"HSV_{num}", init_s_min, 255, empty) cv2.createTrackbar(f"SAT Max_{num}", f"HSV_{num}", init_s_max, 255, empty) cv2.createTrackbar(f"VALUE Min_{num}", f"HSV_{num}", init_v_min, 255, empty) cv2.createTrackbar(f"VALUE Max_{num}", f"HSV_{num}", init_v_max, 255, empty) cv2.namedWindow(f"Parameters_{num}") cv2.resizeWindow(f"Parameters_{num}", 640, 240) cv2.createTrackbar(f"Threshold1_{num}", f"Parameters_{num}", init_thr1, 255, empty) cv2.createTrackbar(f"Threshold2_{num}", f"Parameters_{num}", init_thr2, 255, empty) cv2.createTrackbar(f"Area_{num}", f"Parameters_{num}", init_area, 30000, empty) self.num = num
def initialize_trackbars(initial_trackbar_values): cv.namedWindow("Adaptive Threshold") cv.resizeWindow("Adaptive Threshold", 360, 240) cv.createTrackbar('thresh_val', 'Adaptive Threshold', initial_trackbar_values[0], 1, do_nothing) cv.createTrackbar('adapt_val', 'Adaptive Threshold', initial_trackbar_values[1], 1, do_nothing) cv.createTrackbar("high_threshold", 'Adaptive Threshold', initial_trackbar_values[2], 10, do_nothing) cv.createTrackbar("block_size", 'Adaptive Threshold', initial_trackbar_values[3], 101, do_nothing) cv.createTrackbar("sub_const", 'Adaptive Threshold', initial_trackbar_values[4], 100, do_nothing)
def init(row, col, win_name): # win_name = str(x) + str(y) if win_name in windowses: return cv.namedWindow(win_name, cv.WINDOW_NORMAL) cv.resizeWindow(win_name, WIN_SIZE[0], WIN_SIZE[1]) cv.moveWindow(win_name, col * WIN_SIZE[0], row * WIN_SIZE[1]) windowses.add(win_name)
def initialize_trackbars(initial_trackbar_values): cv.namedWindow("TrackBars") cv.resizeWindow("TrackBars", 360, 240) cv.createTrackbar('min', 'TrackBars', initial_trackbar_values[0], 255, do_nothing) cv.createTrackbar('max', 'TrackBars', initial_trackbar_values[1], 255, do_nothing) cv.createTrackbar("apertureSize", 'TrackBars', initial_trackbar_values[2], 7, do_nothing)
def btn2State(self): global img if self.btn_2.isEnabled(): self.btn_3.setEnabled(True) # print("Btn_2被点击") get_window_jpg() cv2.resizeWindow('image', 640, 480) # get_image_roi(img_cv) lab_data()
def adjust_circle(image, circle): """Manually adjust a circle on an image. Takes an input image and circle(center, radius) and shows a blown up region centered around the circle. Allows the user to adjust the circle using trackbars. Waits for keypress to finish. Returns adjusted circle and keypress.""" # initialize window and trackbars win = 'Adjust Target Circle' cv2.namedWindow(win) cv2.resizeWindow(win, 200, 200) # initialize variables roi, roi_origin = get_circle_roi(image, circle) circle_local = np.copy(circle) circle_local[0] = circle[0] - np.flipud(roi_origin) # scale image to be bigger and allow for easier adjustment scale = cf['roi']['ADJUST_SCALE'] roi = scale_image(roi, scale) circle_local = np.multiply(circle_local, scale) img_circ = np.copy(roi) # Set max radius of circle such that the max diameter is the length # of the region of interest max_radius = roi.shape[0] // 2 # initialize trackbars cv2.createTrackbar('x', win, circle_local[0][0], roi.shape[1], empty_callback) cv2.createTrackbar('y', win, circle_local[0][1], roi.shape[0], empty_callback) cv2.createTrackbar('r', win, circle_local[1], max_radius, empty_callback) keypress = -1 while keypress == -1: cv2.circle(img_circ, (cv2.getTrackbarPos('x', win), cv2.getTrackbarPos('y', win)), cv2.getTrackbarPos('r', win), (0, 0, 0), 1) cv2.imshow(win, img_circ) img_circ = np.copy(roi) keypress = cv2.waitKey(5) adj_circle = ((cv2.getTrackbarPos('x', win) // scale + roi_origin[1], cv2.getTrackbarPos('y', win) // scale + roi_origin[0]), cv2.getTrackbarPos('r', win) // scale) cv2.destroyWindow(win) return adj_circle, keypress
def show_img(img): """ If there is a matched image, the function shows it on screen :param img: image to show on screen """ cv2.namedWindow("Painting rectification", cv2.WINDOW_KEEPRATIO) cv2.imshow("Painting rectification", img) cv2.resizeWindow("Painting rectification", int(img.shape[1] / 2), int(img.shape[0] / 2)) cv2.waitKey(0)
def showPolygon(self, **kw): cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.resizeWindow('image', 1001, 1001) #定义frame的大小 cv2.imshow('image', self.img) if len(kw) > 0: cv2.imwrite( '/Users/sean/Documents/Projects/Algorithm Learn/Packing Algorithm/image/' + kw["_type"] + time.asctime(time.localtime(time.time())) + '.png', self.img) cv2.waitKey(0) cv2.destroyAllWindows()
def __init__(self): cv2.namedWindow("trackBars") cv2.resizeWindow("trackBars", 640, 240) def empty(a): pass cv2.createTrackbar("Hue min", "trackBars", 0, 179, empty) cv2.createTrackbar("Hue max", "trackBars", 179, 179, empty) cv2.createTrackbar("Sat min", "trackBars", 50, 255, empty) cv2.createTrackbar("Sat max", "trackBars", 255, 255, empty) cv2.createTrackbar("Value min", "trackBars", 0, 255, empty) cv2.createTrackbar("Value max", "trackBars", 255, 255, empty)
def trackbarwindow(self): def empty(a): pass cv2.namedWindow(self.winname) cv2.resizeWindow(self.winname, 640, 240) cv2.createTrackbar(self.trackbar_name[0], self.winname, 0, 179, empty) cv2.createTrackbar(self.trackbar_name[1], self.winname, 88, 179, empty) cv2.createTrackbar(self.trackbar_name[2], self.winname, 41, 255, empty) cv2.createTrackbar(self.trackbar_name[3], self.winname, 255, 255, empty) cv2.createTrackbar(self.trackbar_name[4], self.winname, 114, 255, empty) cv2.createTrackbar(self.trackbar_name[5], self.winname, 255, 255, empty)
def findColor( ): #Finds the color of an object by user varying slider to mask out object def empty(a): pass frameWidth = 640 frameHeight = 480 cap = cv2.VideoCapture(0) cap.set(3, frameWidth) cap.set(4, frameHeight) cap.set(10, 150) cv2.namedWindow("HSV") cv2.resizeWindow("HSV", 640, 240) cv2.createTrackbar("Hue Min", "HSV", 0, 179, empty) cv2.createTrackbar("Sat Min", "HSV", 0, 255, empty) cv2.createTrackbar("Val Min", "HSV", 0, 255, empty) cv2.createTrackbar("Hue Max", "HSV", 179, 179, empty) cv2.createTrackbar("Sat Max", "HSV", 255, 255, empty) cv2.createTrackbar("Val Max", "HSV", 255, 255, empty) while True: _, img = cap.read() imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h_min = cv2.getTrackbarPos("Hue Min", "HSV") h_max = cv2.getTrackbarPos("Hue Max", "HSV") s_min = cv2.getTrackbarPos("Sat Min", "HSV") s_max = cv2.getTrackbarPos("Sat Max", "HSV") v_min = cv2.getTrackbarPos("Val Min", "HSV") v_max = cv2.getTrackbarPos("Val Max", "HSV") #print(v_min) lower = np.array([h_min, s_min, v_min]) upper = np.array([h_max, s_max, v_max]) mask = cv2.inRange(imgHSV, lower, upper) result = cv2.bitwise_and(img, img, mask=mask) mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) cv2.imshow("Original", img) cv2.imshow("Mask", mask) cv2.imshow("Result", result) if cv2.waitKey(1) & 11111111 == ord('q'): break cap.release() cv2.destroyAllWindows()
def calc_matrix(reference_points_target): global img cam = VideoCapture(0) # 0 -> index of camera s, img = cam.read() cv2.namedWindow("image", cv2.WINDOW_NORMAL) cv2.resizeWindow("image", 1280, 720) cv2.setMouseCallback("image", draw_circle) while (1): cv2.imshow('image', img) k = cv2.waitKey(20) & 0xFF if k == 27: break elif k == ord("p"): print(mouseX, mouseY) elif k == ord("b"): pos_blue = [mouseX, mouseY] print('Blue Marked at ' + str(pos_blue)) elif k == ord("r"): pos_red = [mouseX, mouseY] print('Red Marked at ' + str(pos_red)) elif k == ord("y"): pos_yellow = [mouseX, mouseY] print('Yellow Marked at ' + str(pos_yellow)) elif k == ord("q"): cv2.destroyAllWindows() break try: pos_blue pos_red pos_yellow except NameError: raise Exception("Not all three reference points were assigned") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # set CV2 color scale to RGB rows, cols, ch = img.shape pts1 = np.float32([pos_blue, pos_red, pos_yellow]) pts2 = np.float32(reference_points_target) M = cv2.getAffineTransform(pts1, pts2) return M
def takeVal(): img = cv2.imread('SysImages/Parameters.png')[:160, :, :] img = cv2.resize(img, (340, 120)) cv2.namedWindow('Parameters') cv2.imshow('Parameters', img) cv2.resizeWindow('Parameters', 640, 240) cv2.createTrackbar('HUE Min', 'Parameters', 150, 255, empty) cv2.createTrackbar('HUE Max', 'Parameters', 190, 255, empty) cv2.createTrackbar('SAT Min', 'Parameters', 195, 255, empty) cv2.createTrackbar('SAT Max', 'Parameters', 255, 255, empty) cv2.createTrackbar('VALUE Min', 'Parameters', 195, 255, empty) cv2.createTrackbar('VALUE Max', 'Parameters', 255, 255, empty) cv2.createTrackbar('Thresh1', 'Parameters', 0, 255, empty) cv2.createTrackbar('Thresh2', 'Parameters', 225, 255, empty) cv2.createTrackbar('Area Min', 'Parameters', 100, 1000, empty)
def detect_color(path): # add track bar def empty(x): pass cv2.namedWindow('TrackBar') cv2.resizeWindow('TrackBar', 640, 240) cv2.createTrackbar('Hue min', 'TrackBar', 0, 179, empty) cv2.createTrackbar('Hue max', 'TrackBar', 179, 179, empty) cv2.createTrackbar('Saturation min', 'TrackBar', 0, 255, empty) cv2.createTrackbar('Saturation max', 'TrackBar', 255, 255, empty) cv2.createTrackbar('Val min', 'TrackBar', 0, 255, empty) cv2.createTrackbar('Val max', 'TrackBar', 255, 255, empty) while True: img = cv2.imread(path) imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # get the values from track bar h_min = cv2.getTrackbarPos('Hue min', 'TrackBar') h_max = cv2.getTrackbarPos('Hue max', 'TrackBar') s_min = cv2.getTrackbarPos('Saturation min', 'TrackBar') s_max = cv2.getTrackbarPos('Saturation max', 'TrackBar') v_min = cv2.getTrackbarPos('Val min', 'TrackBar') v_max = cv2.getTrackbarPos('Val max', 'TrackBar') lower = np.array([h_min, s_min, v_min]) upper = np.array([h_max, s_max, v_max]) mask = cv2.inRange(imgHSV, lower, upper) imgMasked = cv2.bitwise_and(img, img, mask=mask) # cv2.imshow('Original image', img) # cv2.imshow('HSV image', imgHSV) # cv2.imshow('Mask image', mask) # cv2.imshow('Masked image', imgMasked) imgStack = stackImages(0.6, ([img, imgHSV], [mask, imgMasked])) cv2.imshow('Stacked Images', imgStack) cv2.waitKey(1)
def get_image_roi(rgb_image): ''' 获得用户ROI区域的rect=[x,y,w,h] :param rgb_image: :return: ''' # bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR) global g_rect img = rgb_image cv2.namedWindow('image') cv2.resizeWindow('image', 640, 480) while True: cv2.setMouseCallback('image', on_mouse) cv2.resizeWindow('image', 640, 480) cv2.startWindowThread() # 加在这个位置 cv2.imshow('image', img) key = cv2.waitKey(0) if cv2.getWindowProperty('image', cv2.WND_PROP_AUTOSIZE) < 1: break cv2.destroyAllWindows() # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return g_rect
def webCam (): url = "http://172.28.131.139:8080/shot.jpg" cv2.namedWindow("ipcam",cv2.WINDOW_NORMAL) cv2.resizeWindow("ipcam",800,800) while True: imgRes=urllib.request.urlopen(url) imgArray= np.array(bytearray(imgRes.read()),dtype=np.uint8) img =cv2.imdecode(imgArray,-1) cv2.imshow("ipcam",img) img3=np.copy(img) img4=np.copy(img) LINES=Thread(target= houghline_transform, args=(img,)) LINES.start() #ret=LINES.join() ret=result.get() hsv = cv2.cvtColor(img3, cv2.COLOR_BGR2HSV) Gray_scaled_image=Gray_image(hsv) gray_copy=np.copy(Gray_scaled_image) filtered_image2=region_of_interest(img4,gray_copy) #print(ret) #LINES=houghline_transform(img) img2=np.copy(img) #average_slope_intercept(img2,LINES) #_thread.start_new_thread( loop, (ret,gray_copy,img4,filtered_image2 ) ) for line in ret: x1,y1,x2,y2 =line[0] cv2.line(img4,(x1,y1),(x2,y2),(255,255,255),6) #draws a green line with a thickness equal to 3 cv2.line(gray_copy,(x1,y1),(x2,y2),(255,0,0),6) cv2.line(filtered_image2,(x1,y1),(x2,y2),(255,0,0),6) cv2.namedWindow("Gray_scale_with_lines",cv2.WINDOW_NORMAL) cv2.resizeWindow("Gray_scale_with_lines",800,800) cv2.imshow("Gray_scale_with_lines",gray_copy) cv2.namedWindow("Image_with_lines",cv2.WINDOW_NORMAL) cv2.resizeWindow("Image_scale_with_lines", 800, 800) cv2.imshow("Image_with_lines",img4) cv2.namedWindow("filtered",cv2.WINDOW_NORMAL) cv2.resizeWindow("filtered", 800, 800) cv2.imshow("filtered",filtered_image2) _thread.start_new_thread( average_slope_intercept, (img2, ret, ) ) if cv2.waitKey(1)==27: break
def showImage(image_lines, gray_lines, filter): #with_objects=Countour_detection(img,Gray_scaled_image) cv2.namedWindow("image_with_lines", cv2.WINDOW_NORMAL) cv2.resizeWindow("image_with_lines", 200, 200) cv2.imshow("image_with_lines", image_lines) cv2.namedWindow("Filtered_image", cv2.WINDOW_NORMAL) cv2.resizeWindow("Filtered_image", 200, 200) cv2.imshow("Filtered_image", filter) cv2.namedWindow("Gray_scale_with_lines", cv2.WINDOW_NORMAL) cv2.resizeWindow("Gray_scale_with_lines", 200, 200) cv2.imshow("Gray_scale_with_lines", gray_lines) #cv2.imshow("with_objects",with_objects) cv2.waitKey(1)
# Define all the global variables heightImg = 640 widthImg = 480 Image_Resolution_height = 640 Image_Resolution_width = 480 # For Photo from live Webcam feed #img_counter=utilities.webcamfeed(heightImg,widthImg,Image_Resolution_height,Image_Resolution_width) img_counter = 2 #For Live Webcam feed, uncomment next line #if webCamFeed:success, img = cap.read() #else: # Reading the Image # Filepath of Image pathImage = "opencv_frame_{}.png".format(img_counter - 1) img = cv2.imread(pathImage) heightImg, widthImg, _ = img.shape # Trackbars for Threshold 1 and 2 cv2.namedWindow("Threshold Parameters") cv2.resizeWindow("Threshold Parameters", 400, 600) cv2.createTrackbar("Threshold 1", "Threshold Parameters", 60, 255, utilities.nothing) cv2.createTrackbar("Threshold 2", "Threshold Parameters", 60, 255, utilities.nothing) Warped_Img = utilities.process(img, heightImg, widthImg) print(1) utilities.adaptive_thresholding(Warped_Img, heightImg, widthImg)
from cv2 import cv2 import numpy as np img = cv2.imread("Resources/lambo.png") imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) window = cv2.namedWindow("Trackbars") cv2.resizeWindow("Trackbars", 512, 512) cv2.createTrackbar("Hue Min", "Trackbars", 0, 179, lambda x: x) cv2.createTrackbar("Hue Max", "Trackbars", 24, 179, lambda x: x) cv2.createTrackbar("Sat Min", "Trackbars", 88, 255, lambda x: x) cv2.createTrackbar("Sat Max", "Trackbars", 255, 255, lambda x: x) cv2.createTrackbar("Val Min", "Trackbars", 137, 255, lambda x: x) cv2.createTrackbar("Val Max", "Trackbars", 255, 255, lambda x: x) while True: mins = np.array([ cv2.getTrackbarPos("Hue Min", "Trackbars"), cv2.getTrackbarPos("Sat Min", "Trackbars"), cv2.getTrackbarPos("Val Min", "Trackbars") ], dtype=np.uint8) maxes = np.array([ cv2.getTrackbarPos("Hue Max", "Trackbars"), cv2.getTrackbarPos("Sat Max", "Trackbars"), cv2.getTrackbarPos("Val Max", "Trackbars") ], dtype=np.uint8) mask = cv2.inRange(imgHSV, mins, maxes) result = cv2.bitwise_and(img, img, mask=mask)
hor[x] = np.hstack(imgArray[x]) ver = np.vstack(hor) else: for x in range(0, rows): if imgArray[x].shape[:2] == imgArray[0].shape[:2]: imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale) else: imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale) if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR) hor= np.hstack(imgArray) ver = hor return ver cv2.namedWindow("TrackBars") #craeting a trackbar to find optimal values of hue , sat and val cv2.resizeWindow("TrackBars", 640,240) cv2.createTrackbar("Hue Min", "TrackBars",0,179,empty) cv2.createTrackbar("Hue Max", "TrackBars",179,179,empty) cv2.createTrackbar("Sat Min", "TrackBars",0,255,empty) cv2.createTrackbar("Sat Max", "TrackBars",255,255,empty) cv2.createTrackbar("Val Min", "TrackBars",0,255,empty) cv2.createTrackbar("Val Max", "TrackBars",255,255,empty) livecap = cv2.VideoCapture(0) livecap.set(3, 600) # 3 represents height here livecap.set(4, 400) # 4 represents width here livecap.set(10, 1000) # 10 represents brightnes
imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale) else: imgArray[x] = cv2.resize( imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None, scale, scale) if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR) hor = np.hstack(imgArray) ver = hor return ver # Define Trackbars cv2.namedWindow('TrackBars') cv2.resizeWindow('TrackBars', 640, 240) cv2.createTrackbar('Hue Min', 'TrackBars', 0, 179, empty_fn) cv2.createTrackbar('Hue Max', 'TrackBars', 19, 179, empty_fn) cv2.createTrackbar('Sat Min', 'TrackBars', 110, 255, empty_fn) cv2.createTrackbar('Sat Max', 'TrackBars', 240, 255, empty_fn) cv2.createTrackbar('Val Min', 'TrackBars', 153, 255, empty_fn) cv2.createTrackbar('Val Max', 'TrackBars', 255, 255, empty_fn) while True: # Read image file from path path = 'Resources/lambo.png' img = cv2.imread(path) # convert image to HSV imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
def init_window(name, row=0, col=0): cv.namedWindow(name, cv.WINDOW_NORMAL) cv.resizeWindow(name, WIN_SIZE[0], WIN_SIZE[1]) cv.moveWindow(name, col * WIN_SIZE[0], row * WIN_SIZE[1]) warmup_img = np.zeros(shape=(IMG_SIZE[1], IMG_SIZE[0], 3), dtype=np.uint8) show_image(warmup_img, name)
def Varredura(): #realiza a varredura e chama a função de analise de contornos img = Camera() #caso queira desabilitar a camera, é so comentar a linha de cima e usar as de baixo #img = cv2.imread("<endereço da imagem>") #img = cv2.resize(img, (639,479), interpolation = cv2.INTER_AREA) #chama a função de enquadramento img = Enquadramento(img) #a função da janela declarada é impedir q a imagem apareça gigantesca e ñ perca qualidade cv2.namedWindow('Deseja Recortar a imagem?', cv2.WINDOW_NORMAL) cv2.resizeWindow('Deseja Recortar a imagem?', (int(479 * proporcao), 479)) ##### rotacionar 180º para melhor compreenção altura, largura = img.shape[:2] ponto = (largura / 2, altura / 2 ) #ponto no centro da figura, ponto de giro rotacao = cv2.getRotationMatrix2D(ponto, 180, 1.0) img = cv2.warpAffine(img, rotacao, (largura, altura)) ###primeira janela pra corte print("\n\n\n") print("--Deseja recortar a imagem?--") print( "-Sim:\n Selecione clicando e arrastando.\n Confirma com a tecla Enter" ) print("-Não:\n Aperte a tecla Esc\n\n\n") xs, ys, w, h = cv2.selectROI( 'Deseja Recortar a imagem?', img) #permite o usuario cortar a imagem com o mouse cv2.destroyAllWindows() crop_img_true = crop_img_contour = img[ys:ys + h, xs:xs + w] #salvandoos dados do corte cortada = True if crop_img_true.shape[0] < 1: cortada = False crop_img_true = crop_img_contour = img print("\n\n\n") print( "--Utilize as barras para evidenciar, da melhor forma possível, os objetos desejados--" ) print( "--O filtro dinâmico possui limitações, logo, talvez não seja possível evidenciar todos os objetos desejados de um só vez--" ) #filtro dinamico desejo = "b" while 1: x, y, z, a, b, c = ( tr.tracker(crop_img_true) ) #biblioteca que gera filtro de cores de modo iterativo crop_img_true = cv2.cvtColor( crop_img_true, cv2.COLOR_BGR2HSV ) #é necessario converter para hsv para passar o filtro #criando imagem base pra varredura com o contorno do filtro de cores mask_inRange = cv2.inRange(crop_img_true, (x, y, z), (a, b, c)) #lógica para sobreposição de filtros, necessário caso o usuário queira evidencia cores distantes no espectro HSVe com intervalos if desejo == "a": mask_inRange = cv2.resize(mask_inRange, (int(479 * proporcao), 479), interpolation=cv2.INTER_AREA) mask_inRange_temp = cv2.resize(mask_inRange_temp, (int(479 * proporcao), 479), interpolation=cv2.INTER_AREA) for y in range(0, mask_inRange.shape[0]): #percorre linhas for x in range(0, mask_inRange.shape[1]): #percorre colunas #mask eh uma imagem composta apenas de 0 e 255 if (mask_inRange_temp[y][x] == (255)): mask_inRange[y][x] = (255) mask_inRange = cv2.resize(mask_inRange, (int(2500 * proporcao), 2500), interpolation=cv2.INTER_AREA) print("--Deseja avidenciar mais objetos?--") print(" a - Sim \n b - Não") desejo = input() if desejo == "a": mask_inRange_temp = mask_inRange crop_img_true = cv2.cvtColor(crop_img_true, cv2.COLOR_HSV2BGR) #caso o usuário envio qualquer coisa diferente de a, será considerado b else: break #caso o usuário opte por recoertar a imagem, é necessario corrigir as medidas if cortada == True: blank_space_black = np.zeros((img.shape[0], img.shape[1]), np.uint8) blank_space_black[:] = (0) blank_space_black[ys:ys + h, xs:xs + w] = mask_inRange mask_inRange = blank_space_black crop_img_true = crop_img_contour = img #etapa importante para que a função findContours funcione sem problemas _, threshold = cv2.threshold(mask_inRange, 250, 255, cv2.THRESH_BINARY) #varredura de contornos contours = [] contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) #listas de bordas contornos_reais = [] total_objetos = 0 # tirando objetos menores que o minimo... retira ruido for cnt in contours: if cv2.contourArea(cnt) >= maxi: contornos_reais.append(cnt) total_objetos += 1 print("\n\n") print("-- Total de objetos encontrados", total_objetos, " --") # todos os dados são obtidos atraves da mascara, uma imagem praticamente binária. #as edições (contornos, escrever o ID no centro do objeto) são feitas em cima da imagem crop_img_contour que é a mesma imagem justificada, enquadrada lá do inicio #desenhar contornos cv2.drawContours(crop_img_contour, contornos_reais, -1, (0, 255, 0), 5) crop_img_contour, tabela = Identificar_objeto( contornos_reais, crop_img_contour, img) #chamar a função Identificar_objetos img_final = cv2.resize(crop_img_contour, (850, 512), interpolation=cv2.INTER_AREA) cv2.imwrite("img_final.jpg", img_final) #salvando a imagem na pasta do programa ###tabela tabela_df = pd.DataFrame(data=tabela, columns=[ 'Id', 'Centro_X', 'Centro_Y', 'Ângulo', ]) tabela_df.to_csv("tabela.csv") return tabela_df, img_final
# Ref: https://github.com/PyUserInput/PyUserInput # Usage: # m.click(0, 0, 1) 使用 X11 坐标 # k.type_string('Hello, World!') m = PyMouse() k = PyKeyboard() # Screen detection print('[加载]屏幕参数') x11_x, x11_y = m.screen_size() pil_x, pil_y = ImageGrab.grab().size DPI_times = pil_x / x11_x EMULATOR_HEADER = 39 EMULATOR_BOTTOM = 42 cv2.namedWindow('output', cv2.WINDOW_NORMAL) cv2.resizeWindow('output', 500, 500) cv2.moveWindow('output', int(x11_x) - 500, int(x11_y) - 500) print('[加载]X11 size:', (x11_x, x11_y)) print('[加载]PIL size:', ImageGrab.grab().size) print('[加载]DPI times:', DPI_times) # Helpers - 图像处理 screen_data = None class ScanIter(object): def __init__(self, startp, endp): self.start_x, self.start_y = startp self.end_x, self.end_y = endp def __iter__(self):
u, v = img.shape[:2] # 找到棋盘格角点 ret, corners = cv2.findChessboardCorners(gray, (w,h),None) # 如果找到足够点对,将其存储起来 if ret == True: print("i:", i) i = i+1 # 在原角点的基础上寻找亚像素角点 cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) #追加进入世界三维点和平面二维点中 objpoints.append(objp) imgpoints.append(corners) # 将角点在图像上显示 cv2.drawChessboardCorners(img, (w,h), corners, ret) cv2.namedWindow('findCorners', cv2.WINDOW_NORMAL) cv2.resizeWindow('findCorners', 640, 480) cv2.imshow('findCorners',img) cv2.waitKey(200) cv2.destroyAllWindows() #%% 标定 print('正在计算') #标定 ret, mtx, dist, rvecs, tvecs = \ cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) print("ret:",ret ) print("mtx:\n",mtx) # 内参数矩阵 print("dist畸变值:\n",dist ) # 畸变系数 distortion cofficients = (k_1,k_2,p_1,p_2,k_3) print("rvecs旋转(向量)外参:\n",rvecs) # 旋转向量 # 外参数 print("tvecs平移(向量)外参:\n",tvecs ) # 平移向量 # 外参数
# python object_size.py --image images/example_03.png --width 3.5 # python object_size.py --image images/test_01.jpg --width 1 # python object_size.py --image images/test_02.jpg --width 1 # python object_size.py --image images/test_04.jpg --width 0.787402 # import the necessary packages from scipy.spatial import distance as dist from imutils import perspective from imutils import contours from cv2 import cv2 import numpy as np import argparse import imutils cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.resizeWindow('image', 1920, 1080) def midpoint(ptA, ptB): return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5) # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the input image") ap.add_argument("-w", "--width", type=float, required=True, help="width of the left-most object in the image (in inches)") args = vars(ap.parse_args()) # load the image, convert it to grayscale, and blur it slightly image = cv2.imread(args["image"]) cv2.imshow("image", image)
import math from sympy import Point, Line, Circle, intersection, Ray, pi from cv2 import cv2 as cv from sympy import plot_implicit, cos, sin, symbols, Eq, And from sympy import symbols from sympy.plotting import plot import matplotlib.pyplot as plt from numba import jit, cuda def nothing(x): pass cv.namedWindow('Image', cv.WINDOW_NORMAL) cv.resizeWindow('Image', 600, 600) def during_collision(cue_point, radius, stick_point, ball_coord): future_point = cue_point collision_ball_info = cue_point min_distance = 1e9 temp_ray = Ray(cue_point, stick_point) temp_Line = Line(cue_point, stick_point) temp_circle = Circle(cue_point, radius) temp_collision_points = intersection(temp_Line, temp_circle) if temp_ray.contains(temp_collision_points[0]): white_ray = Ray(cue_point, temp_collision_points[1]) else: