def main(): global countClicks, coordinates, copyimage cv2.resizeWindow(windowname, 700, 700) while (countClicks < 4): preseedKey = cv2.waitKey(1) cv2.imshow(windowname, image) if preseedKey & 0xFF == 27: break pointone = np.float32( [[coordinates[0], coordinates[1]], [coordinates[2], coordinates[3]], [coordinates[4], coordinates[5]], [coordinates[6], coordinates[7]]]) pointtwo = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]]) perspective = cv2.getPerspectiveTransform(pointone, pointtwo) output = cv2.warpPerspective(copyimage, perspective, (310, 310)) cv2.imshow("Output Image", output) cv2.waitKey(0) cv2.destroyAllWindows()
def find_routes(image): global hsv # Create a black image, a window and bind the function to window img = cv2.imread(image, 1) rows,cols,channels = img.shape colorImg = np.zeros((rows,cols,3), np.uint8) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) cv2.namedWindow(image, cv2.WINDOW_NORMAL) cv2.namedWindow('Wall', cv2.WINDOW_NORMAL) cv2.namedWindow('ColorMask', cv2.WINDOW_NORMAL) cv2.namedWindow('Mask', cv2.WINDOW_NORMAL) cv2.resizeWindow(image, 500, 500) cv2.setMouseCallback(image, get_route_mask) phase = 1 while(1): if routeChosen: imgRoute = cv2.bitwise_and(img, img, mask = mask_inv) colorRoute = cv2.bitwise_and(colorImg, colorImg, mask = mask) newImg = cv2.add(imgRoute,colorRoute) cv2.imshow(image, newImg) cv2.imshow('Wall', imgRoute) cv2.imshow('ColorMask', colorRoute) cv2.imshow('Mask', mask) change_color(phase) colorImg[:,:] = (b,g,r) if phase == 60: phase = 0 else: phase = phase + 1 else: cv2.imshow(image, img) if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows()
def get_start_points(image): window = cv2.namedWindow(MAZE_NAME, cv2.WINDOW_NORMAL) cv2.resizeWindow(MAZE_NAME, 900,900) cv2.imshow(MAZE_NAME,image) cv2.moveWindow(MAZE_NAME,100,100) imageProcessor = ImageProcessor(image) start_x,start_y = imageProcessor.getDefaultStart(image) end_x, end_y = imageProcessor.getDefaultEnd(image) print("Please \'A\' to use default start and end points, or press \'S\' to choose your own)") key = cv2.waitKey(2000) print key if key == ord('a') or key == -1: print("Using Default Start and End Points") imageProcessor = ImageProcessor(image) start_x,start_y = imageProcessor.getDefaultStart(image) end_x, end_y = imageProcessor.getDefaultEnd(image) print("Start Point: {0}, End Point: {1}".format((start_x,start_y),(end_x,end_y))) elif key == ord ('s'): print("Please select a start point") start_x,start_y = get_user_selected_point(image) print ("Start Point: {0}, please select an end point".format((start_x,start_y))) end_x,end_y = get_user_selected_point(image) print("End Pont: {0}".format((end_x,end_y))) cv2.destroyAllWindows() return start_x,start_y,end_x,end_y
def __SetupWindowSliders(self): """Define windows for displaying the results and create trackbars.""" # Windows. cv2.namedWindow("Original") cv2.namedWindow("Threshold") cv2.namedWindow("Results") cv2.namedWindow("TrackBars", cv2.WINDOW_NORMAL) cv2.resizeWindow("TrackBars", 500, 600) # Threshold value for the pupil intensity. cv2.createTrackbar("pupilThr", "TrackBars", 90, 255, self.__OnSlidersChange) # Threshold value for the glint intensities. cv2.createTrackbar("glintThr", "TrackBars", 240, 255, self.__OnSlidersChange) # Threshold value for the iris intensity. cv2.createTrackbar("irisThr", "TrackBars", 145, 255, self.__OnSlidersChange) # Define the minimum and maximum areas of the pupil. cv2.createTrackbar("pupilMinSize", "TrackBars", 20, 200, self.__OnSlidersChange) cv2.createTrackbar("pupilMaxSize", "TrackBars", 200, 200, self.__OnSlidersChange) # Define the minimum and maximum extends of the pupil. cv2.createTrackbar("pupilMinExtend", "TrackBars", 1, 100, self.__OnSlidersChange) cv2.createTrackbar("pupilMaxExtend", "TrackBars", 100, 100, self.__OnSlidersChange) # Define the minimum and maximum areas of the pupil glints. cv2.createTrackbar("glintMinSize", "TrackBars", 1, 2000, self.__OnSlidersChange) cv2.createTrackbar("glintMaxSize", "TrackBars", 2000, 2000, self.__OnSlidersChange) # Define the minimum and maximum allowed distance between two glints cv2.createTrackbar('glintMinDist', 'TrackBars', 49, 100, self.__OnSlidersChange) cv2.createTrackbar('glintMaxDist', 'TrackBars', 51, 100, self.__OnSlidersChange) # Define the minimum and maximum areas of the pupil iris. cv2.createTrackbar("irisMinSize", "TrackBars", 1, 2000, self.__OnSlidersChange) cv2.createTrackbar("irisMaxSize", "TrackBars", 2000, 2000, self.__OnSlidersChange) # Value to indicate whether to run or pause the video. cv2.createTrackbar("Stop/Start", "TrackBars", 0, 1, self.__OnSlidersChange)
def show_codewords(code_dict, wtype, wshape): line = concatinate_all_imgs(code_dict, wtype, wshape) cv2.namedWindow("str(i)",2) cv2.resizeWindow("str(i)", 800, 600) cv2.imshow("str(i)", line) cv2.waitKey()
def imageIdentify(Box): global config try: #Gets and processes the given box selection #Get box size from it's slider Selection_Frame = Box.name #Selection Frame and Box share Name Box.size = cv2.getTrackbarPos('Size', Selection_Frame) Box.threshold = cv2.getTrackbarPos('Threshold', Selection_Frame) #Set the min box size if Box.size <10: Box.size = 10 #gets and process the selection Box.selection = getSelection(Box.location[0], Box.location[1], Box.size) Box.selection = preprocessImage(Box.selection, Selection_Frame, Box.threshold) cv2.imshow(Selection_Frame, Box.selection) #show proccesed image in selection window cv2.resizeWindow(Selection_Frame, 300, 300) #keeps the windows a set size so you cant see trackbars #convert image to number ValueList = getValueList(Box.segCoordinates, Box.selection) Value = convertToInt(ValueList) return Value except: print "Selection Error: Out of Bounds" return None
def setupWindow(): filename = getUserSelectedImage() imageProcessor = ImageProcessor(cv2.imread(filename,0)) colourImage = cv2.imread(filename,1) image = imageProcessor.getThresholdedImage(False) granularity = imageProcessor.get_granularity(image, 100) print("Granularity: {0}".format(granularity)) start_x,start_y,end_x,end_y = get_start_points(image) image = imageProcessor.encloseMaze(image) pg = PolicyGenerator(image) rows,cols = pg.get_critical_grid() graph,mapping = pg.get_reduced_graph([rows,cols]) policy = pg.generate_policy((end_x,end_y)) solution = solve_using_policy(policy,(start_x,start_y),(end_x,end_y)) imageProcessor.draw_policy(colourImage,policy) imageProcessor.mark_point((end_x,end_y),3,(255,0,0),colourImage) #cv2.imshow(MAZE_NAME,policy_image) mazerunner = MazeSolver(image,granularity) #solution = mazerunner.solveMaze(start_x,start_y,end_x,end_y) if(not solution): cv2.imshow(MAZE_NAME,image) else: solvedImage = draw_solution(solution, colourImage) solvedImage = imageProcessor.mark_point((start_x,start_y),3,(255,0,0),solvedImage) window = cv2.namedWindow("Solved Image", cv2.WINDOW_NORMAL) cv2.resizeWindow("Solved Image", 900,900) cv2.moveWindow("Solved Image",100,100) cv2.imshow("Solved Image",solvedImage) print("Press any key to exit") cv2.waitKey(0) cv2.destroyAllWindows
def userSelectBed(self, img): """ Opens window and prompts user to select BED Input: Filtered image. Output: None """ # Set up window & call back windowName = 'Left click base of bubble. Press Esc to exit.' cv2.namedWindow(windowName,cv2.WINDOW_NORMAL) # Can be resized cv2.resizeWindow(windowName, self.w*3, self.h*3) # Resize window cv2.setMouseCallback(windowName, self.mouseCallback) # Set callback imgDefault = img # Ideally this resets the image later while True: # Plot cursor click if self.bed: h = self.bed else: h = 0 cv2.line(img, (-1000,h), (1000,h), (0,0,0)) cv2.imshow(windowName, img) img = imgDefault k = cv2.waitKey(4) & 0xFF # Basically delay 1000 ms #print 'BED is currently: ', self.bed if k == 27: # Press escape to exit break cv2.destroyAllWindows()
def main(): rospy.init_node(node_name) # check to see if launch file remaps this try: cv2.namedWindow(win1_name, flags=cv2.cv.WINDOW_NORMAL) #see if flag is necessary # cv2.NamedWindow(win2_name, flags=WINDOW_NORMAL) cv2.moveWindow(win1_name,200,0) # cv2.MoveWindow(win2_name,200,300) cv2.resizeWindow(win1_name,100,300) # cv2.ResizeWindow(win2_name,100,300) cv2.startWindowThread() rospy.on_shutdown(cleanup) # rate = rospy.Rate(freq) sub_RBG = rospy.Subscriber("/camera/rgb/image_color", Image, callback_rbg) # sub_depth = rospy.Subscriber("/camera/depth/image_raw", Image, callback_depth) print('==========Initializing Subscribers=====') rospy.sleep(1) # while not rospy.is_shutdown(): # rospy.rate=1 # rospy.wait_for_message("/camera/rgb/image_color", Image, timeout=None) # k = cv2.waitKey(0) & 0xFF # if k==27: # cleanup() # # rate.sleep() rospy.spin() except KeyboardInterrupt: print "Shutting down" cleanup()
def draw_trajectories(file, trajectories, _time, scale, l): cap = cv2.VideoCapture(file) cv2.namedWindow('frame', cv2.WINDOW_NORMAL) cv2.resizeWindow('frame', int(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH) * scale), int(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT) * scale)) i = 0 while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) for p in trajectories: if (p[0] >= i - l) and (p[0] <= i + l): for j in range (2, i - p[0]): cv2.line(frame, (p[2*(j-1)-1], p[2*(j-1)]), (p[2*j-1],p[2*j]), (0,255,0), 1) #cv2.circle(frame, (p[2*j-1],p[2*j]), 1, (0,255,0)) # Display the resulting frame cv2.imshow('frame',frame) time.sleep(0.033 * _time) i += 1 if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
def __init__(self, w=640, h=480, resizable=False): super(OpencvFramework, self).__init__() if fwSettings.onlyInit: # testing mode doesn't initialize pygame return self._viewZoom = 10.0 self._viewCenter = None self._viewOffset = None self.screenSize = None self.fps = 0 self.screen = np.zeros((h, w, 3), np.uint8) if resizable: cv2.namedWindow(self.name, getattr(cv2,'WINDOW_NORMAL',0)) cv2.resizeWindow(self.name, w, h) else: cv2.namedWindow(self.name, getattr(cv2, 'WINDOW_AUTOSIZE', 1)) cv2.setMouseCallback(self.name, self._on_mouse) self._t0 = time.time() self.textLine = 30 self._font_name, self._font_scale, self._font_thickness = cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1 (_,self._font_h),_ = cv2.getTextSize("X",self._font_name,self._font_scale,self._font_thickness) self.screenSize = b2Vec2(w,h) self.renderer = OpencvDraw(surface=self.screen, test=self) self.world.renderer=self.renderer self.viewCenter = (0,20.0) self.groundbody = self.world.CreateBody()
def dispIm(): if di == 1: cv2.namedWindow("Frame",cv2.WINDOW_NORMAL) cv2.namedWindow("Mask",cv2.WINDOW_NORMAL) cv2.resizeWindow("Frame",900,601) #cv2.resizeWindow("Mask",600,301) cv2.moveWindow("Frame",10,30) cv2.moveWindow("Mask",20,20) cv2.imshow("Mask",Mask) cv2.imshow("Frame",Frame) k = cv2.waitKey(0) & 0xff elif di == 2: #cv2.namedWindow("ResIm",cv2.WINDOW_NORMAL) #cv2.setWindowProperty( # "ResIm", cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN) #cv2.moveWindow("ResIm",30,200) #cv2.imshow("ResIm",resim) cv2.imshow("Frame",Frame) k = cv2.waitKey(0) & 0xff #cv2.destroyWindow("ResIm") #cv2.waitKey(0) & 0xff elif di == 3: cv2.namedWindow("Greyres",cv2.WINDOW_NORMAL) cv2.resizeWindow("Greyres",900,601) cv2.moveWindow("Greyres",300,400) cv2.imshow("Greyres",greyres2) # greyres2 k = cv2.waitKey(0) & 0xff cv2.imshow("Greyres",greyresE) k = cv2.waitKey(0) & 0xff cv2.destroyWindow("Greyres")
def main(): image = data.astronaut() image = ia.imresize_single_image(image, (64, 64)) print("image shape:", image.shape) print("Press any key or wait %d ms to proceed to the next image." % (TIME_PER_STEP,)) k = [ 1, 3, 5, 7, (3, 3), (1, 11) ] cv2.namedWindow("aug", cv2.WINDOW_NORMAL) cv2.resizeWindow("aug", 64*NB_AUGS_PER_IMAGE, 64) for ki in k: aug = iaa.MedianBlur(k=ki) img_aug = [aug.augment_image(image) for _ in range(NB_AUGS_PER_IMAGE)] img_aug = np.hstack(img_aug) print("dtype", img_aug.dtype, "averages", np.average(img_aug, axis=tuple(range(0, img_aug.ndim-1)))) title = "k=%s" % (str(ki),) img_aug = ia.draw_text(img_aug, x=5, y=5, text=title) cv2.imshow("aug", img_aug[..., ::-1]) # here with rgb2bgr cv2.waitKey(TIME_PER_STEP)
def show_images(path1, path2, window_name=None, separator_size=5, max_height=480): if window_name is None: window_name = 'Compare' image_left = open_image(path1) image_right = open_image(path2) image_left, image_right = resize_images(image_left, image_right) width_left, height_left = image_dimensions(image_left) width_right, height_right = image_dimensions(image_right) total_height = max(height_left, height_right) total_width = width_left + separator_size + width_right separator_image = np.zeros((total_height, separator_size, 3), np.uint8) total_image = np.concatenate([image_left, separator_image, image_right], 1) resized_height = min(total_height, max_height) resized_width = resized_height * total_width / total_height cv2.putText(total_image, "Use arrows to choose the image with best quality", (50, 50), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0)) cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(window_name, resized_width, resized_height) cv2.imshow(window_name, total_image) return window_name
def Create_Window(self, State): ''' create window with window name and current state. ''' cv2.namedWindow(State, flags=0) cv2.resizeWindow(State, self.VisualParamDict['resolutionWid'], self.VisualParamDict['resolutionHgt']) cv2.moveWindow(State, 50, 50)
def disk_filtering(rgb, minPixel, maxPixel, debug=False): """ Detects disk/circle and masks the rest :param rgb: RGB frame :param minPixel: minimum pixel size of the disks :param maxPixel: maximum pixel size of the disks :return: grey mask where disks are white squares and the rest is black """ # detect white shades inverseGrey = cv2.cvtColor(cv2.bitwise_not(rgb), cv2.COLOR_RGB2GRAY) circularity = 1.0 # = circle keypoints = blob_detector(inverseGrey, minPixel, maxPixel, circularity) # setting disks to white squares and rest to black diskMask = inverseGrey.copy() diskMask[:] = 0 for kp in keypoints: i = int(np.round(kp.pt[1])) j = int(np.round(kp.pt[0])) diskMask = cv2.circle(diskMask, (i, j), 10, 255, -1) if debug: cv2.namedWindow('disk filtering', cv2.WINDOW_NORMAL) cv2.resizeWindow('disk filtering', 1200, 1200) cv2.imshow('disk filtering', diskMask) return diskMask
def white_patches_masking(frame, whiteBounds = ([0, 0, 225], [10, 30, 255]), debug=False): """ Detection white colored pixels, dilates them and returns resulting grey scale mask :param frame: BGR frame :param whiteBounds: bounds of the color white, (low, high) = ([r,g,b], [R,G,B]) :param dilatationKernel: dilatation kernel, (nb x pixels, nb y pixels) :return: grey scale frame masking out white patches """ maskWhite = color_detection(frame, colorBounds=whiteBounds) # Dilate and blur white patches maskWhite = cv2.dilate(maskWhite, None, iterations=2) maskWhite = cv2.GaussianBlur(maskWhite, (51, 51), 0) # find contours cnts = cv2.findContours(maskWhite.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] # Fill contours with white cv2.drawContours(maskWhite, cnts, -1, (255, 255, 255), thickness=-1) # Invert mask maskWhite = 255 - maskWhite if debug: cv2.namedWindow('white detection', cv2.WINDOW_NORMAL) cv2.resizeWindow('white detection', 1200, 1200) cv2.imshow('white detection', maskWhite) return maskWhite
def onScreen(self, degrees=None, scaleFactor=1): """I need something to display these things for debugging. This uses OpenCV to display in a no-frills, any-key-to-dismiss window.""" if degrees: im = Image.fromarray(self.rotate(degrees)) msg = "{} degree rotation - any key/click to continue".format(degrees) else: im = Image.fromarray(self.array) msg = "any key/click to continue" caption = "image display - any key to close" cv2.namedWindow(caption, 0) shape = im.shape width = int(shape[1] * scaleFactor) height = int(shape[0] * scaleFactor) cv2.resizeWindow(caption, width, height) # cv2.setMouseCallback(caption, kill_window) cv2.imshow(caption, im) cv2.startWindowThread() cv2.waitKey(0) cv2.destroyWindow(caption)
def draw_points_on_img(img_path, pts, show=True): img = cv2.imread(img_path, 1) if pts != None: numPts = pts.shape[0] scaleSiz = np.min((img.shape[0], img.shape[1])) prad = int(5. * scaleSiz / 256.) for pp in xrange(0, numPts): cpp = pts[pp] cv2.circle(img, (int(cpp[0]), int(cpp[1])), prad + 2, (255, 255, 255), -1) # cv2.cv.FILLED cv2.circle(img, (int(cpp[0]), int(cpp[1])), prad + 0, (0, 0, 255), -1) # cv2.cv.FILLED if not show: return img screen_res = 1280, 720 scale_width = screen_res[0] / img.shape[1] scale_height = screen_res[1] / img.shape[0] scale = min(scale_width, scale_height) window_width = int(img.shape[1] * scale) window_height = int(img.shape[0] * scale) cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL) cv2.resizeWindow('dst_rt', window_width, window_height) cv2.imshow('dst_rt', img) cv2.waitKey(0) cv2.destroyAllWindows()
def __init__(self, name, width=None, height=None): self.name = name if width is None or height is None: full_width_height = guess_fullscreen_width_height() if width is None: width = full_width_height[0] if height is None: height = full_width_height[1] self.width = width self.height = height self.image = None cv2.namedWindow(name) # If we don't do this apparently useless re-creation and resize then # the window appears under the dock in Mac OSX. cv2.namedWindow(name, cv2.WINDOW_NORMAL) cv2.resizeWindow(name, self.width, self.height) # This doesn't seem to work, fails with: # error: (-27) NULL window in function cvSetModeWindow_COCOA # # cv2.setWindowProperty( # "Name", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) self.show_image( mel.lib.common.new_image( self.width, self.height))
def __init__(self, name, video_src): #common self.name = name cv2.namedWindow(name, cv2.WINDOW_NORMAL) cv2.resizeWindow(name, 1920/2,1080/2) global capture capture = cv2.VideoCapture(video_src) self.cam = capture global frame _, frame = capture.read() global prev_frame prev_frame = frame global frame_gray frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) global prev_gray prev_gray = frame_gray global canvas, edges canvas = np.zeros_like(frame) edges = np.zeros_like(frame) global gothue, red_filter gothue = Object("pepper_red") red_filter = FT.ColorFilter("red", FT.filter_red) self.frame_idx = 0 #camera movement tracking self.track_len = 10 self.detect_interval =4 self.camera_tracker = self.__camera_tracker(self)
def onScreen(self, args=dict()): """I need something to display these things for debugging. This uses OpenCV to display in a no-frills, any-key-to-dismiss window.""" if 'windowHeight' not in args: args['windowHeight'] = 500 if 'delayAutoClose' not in args: args['delayAutoClose'] = 10000 if 'scaleFactor' not in args: height = float(self.data['spatialShape'][0]) args['scaleFactor'] = float(args['windowHeight'])/height if 'message' not in args: args['message'] = "image display - any key to close" # def kill_window(event): # cv2.destroyWindow(args['message']) cv2.namedWindow(args['message'], 0) shape = self.data['spatialShape'] width = int(shape[1] * args['scaleFactor']) height = int(shape[0] * args['scaleFactor']) cv2.resizeWindow(args['message'], width, height) # cv2.setMouseCallback(args['message'], kill_window) cv2.imshow(args['message'], self.array) cv2.startWindowThread() cv2.waitKey(args['delayAutoClose']) cv2.destroyWindow(args['message'])
def geo_ref_contours(surfTurbArea, uav, debug=False): """ Geo-references surface turbulence areas :param surfTurbArea: frame of surface turbulence areas :param uav: UAV object :return: geo-referenced contours """ # Find contours from white areas imgray = cv2.cvtColor(surfTurbArea,cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray,127,255,0) im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) if debug: im = cv2.drawContours(surfTurbArea, contours, -1, (0,255,0), 3) cv2.namedWindow('Areas & contours', cv2.WINDOW_NORMAL) cv2.resizeWindow('Areas & contours', 1200, 1200) cv2.imshow('Areas & contours', im) # Reformating contoursList = [] for cnt in contours: coordsList = [] for coords in cnt: coordsList.append(tuple(coords[0])) contoursList.append(coordsList) # Georeference contours contoursInDeg, contoursInM = geo_ref_tracks(contoursList, surfTurbArea, uav, debug=debug) return contoursInDeg
def recog(pic): hsv = cv2.cvtColor(pic, cv2.COLOR_RGB2HSV) binary = cv2.adaptiveThreshold(hsv[:,:,2] ,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY_INV, 15, 3) lines = cv2.HoughLinesP(binary, 1, np.pi/360, 150, None, 20 , 1) l = len(lines) for x1, y1, x2, y2 in lines[:,0,:]: cv2.line(pic, (x1, y1), (x2, y2), (0,0,255), 1, cv2.LINE_AA) x, y, n = 0, 0, 0 for i in range(0,l): for j in range(i,l): if i != j: inter = intersection(lines[i,0,:], lines[j,0,:]) if inter: x += inter[0] y += inter[1] n += 1 cv2.circle(pic,(int(inter[0]), int(inter[1])), 1, (255,0,0), -1) #cv2.namedWindow('check', cv2.WINDOW_NORMAL) #cv2.imshow('check', pic) #cv2.resizeWindow('check', 600, 600) cv2.namedWindow('check', cv2.WINDOW_NORMAL) cv2.imshow('check', pic) cv2.resizeWindow('check', 600, 600) cv2.waitKey() return [round(x/n,0), round(y/n,0)]
def imshow(name, title, _in): img = None # Load img if necessary if isinstance(_in, str): img = imread_rotated(_in) elif isinstance(_in, np.ndarray): img = _in # Load exception if input argument invalid if img is None: raise TypeError('Expected file path or image') # Create window if necessary global windows if name not in windows: windows[name] = cv.namedWindow(name, cv.WINDOW_OPENGL | cv.WINDOW_KEEPRATIO) (h, w, _) = img.shape if h < w: ratio = 1280. / w else: ratio = 800. / h h *= ratio w *= ratio img = cv.resize(img, None, fx=ratio, fy=ratio) cv.imshow(name, img) cv.setWindowTitle(name, title) cv.resizeWindow(name, int(w), int(h))
def vizualize_head(img, boxes, path_img, mask_image_path): k = 1 for i,box in enumerate(boxes): (x, y, w, h) = box #if valid_box(box, mask_image_path): cv2.rectangle(img, (x,y),(x+w,y+h),(0,0,255),10) # Create cropped image from box current_output_image = img[y:y+h, x:x+w] original_img_name = path_img.split('/')[-1] current_output_name = original_img_name.split('.')[0] + '_' + str(k) +'.png' current_output_path = 'data/heads/'+current_output_name cv2.imwrite(current_output_path, current_output_image) k += 1 #else: #cv2.rectangle(img, (x,y),(x+w,y+h),(0,255,0),2) #cv2.putText(img, str(i), (x,y),cv2.FONT_HERSHEY_PLAIN, 6, 10, thickness=5) print i,'\t' , path_img, '\t' , x, ' ',y,' ',w,' ',h screen_res = 1280, 720 scale_width = screen_res[0] / float(img.shape[1]) scale_height = screen_res[1] / float(img.shape[0]) scale = min(scale_width, scale_height) window_width = int(img.shape[1] * scale) window_height = int(img.shape[0] * scale) cv2.namedWindow('window', cv2.WINDOW_NORMAL) cv2.resizeWindow('window', window_width, window_height) tmp = cv2.resize(img,(window_width,window_height)); #cv2.imshow('window',tmp) #cv2.waitKey(0) cv2.destroyAllWindows()
def recogChessPattern(pic): gray = cv2.cvtColor(pic, cv2.COLOR_RGB2GRAY) black = np.empty((20,20)) white = np.empty((20,20)) black[:,:] = 0 white[:,:] = 255 template = np.append(np.append(black, white, axis=1), np.append(white, black, axis=1), axis=0) gray = gray.astype(np.uint8) template = template.astype(np.uint8) res = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) pic[max_loc[1] + 20, max_loc[0]+20] = [0,255,0] cv2.namedWindow('check', cv2.WINDOW_NORMAL) cv2.imshow('check', pic) cv2.resizeWindow('check', 600, 600) cv2.waitKey() return (max_loc[0] + 20, max_loc[1]+20)
def Show(self): cv2.namedWindow("Clock", cv2.WINDOW_NORMAL) #cv2.setMouseCallback("Clock", Clock.click) # display the image and wait for a keypress video_capture = cv2.VideoCapture(0) while True: key = cv2.waitKey(1) & 0xFF # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) TRACKER.color = int(np.mean(frame)) cv2.imshow("Clock", np.array(self.Run()))# [:, :, ::-1]) #Clicking s toggles the size of the window. if key == ord('s') or key == ord('S'): TRACKER.startSmall = not TRACKER.startSmall if TRACKER.startSmall: cv2.resizeWindow("Clock", 400, 422) #22px = size of MacOSX window bar if not TRACKER.startSmall: cv2.resizeWindow("Clock", 700, 722) if key == ord(' '): break video_capture.release() cv2.destroyAllWindows()
def __resizeWindow(self): height = 0 if not self.paramCount: height = 76 else: height = self.paramCount * 19 cv2.resizeWindow(self.windowName, 500, height)
def main(): #orig_imgs = ['photoset/cleaned/7,49/IMG_2654.JPG'] # Square, slight angle orig_imgs = glob.glob('photoset/cleaned/*/*.JPG') def img_onchange(x): filename = orig_imgs[cv2.getTrackbarPos('img', 'config')] img = cv2.imread(filename) print filename ret = get_white_rectangles(img, DEBUG=True) for r in ret: print r[1] # just the quads img_windows = ['img', 'blur', 'thresh', 'debug_display'] for i in range(len(img_windows)): w = img_windows[i] cv2.resizeWindow(w, WINDOW_WIDTH, WINDOW_HEIGHT) cv2.moveWindow(w, WINDOW_X_OFFSET + WINDOW_WIDTH * i, WINDOW_Y_OFFSET) cv2.namedWindow('config', cv2.WINDOW_AUTOSIZE) cv2.resizeWindow('config', 600, 60) cv2.createTrackbar('img', 'config', 0, len(orig_imgs), img_onchange) img_onchange(0) cv2.waitKey()
# ファイルリストのうちインデックス番号が cnt のものを str 型で path 変数に格納 path = str(filelist[cnt]) # pathlist というリストにこれを格納 pathlist.append(path) # 格納した path をコマンドライン表示 print(path + " ", end='') # 通し番号をコマンドライン表示 print(int(cnt), "", end="") # 入力画像読み込み read = cv2.imread(path) # 表示するWindow名 window_name = "annotation window" # 入力画像の表示 cv2.namedWindow(window_name, flags=cv2.WINDOW_GUI_NORMAL) cv2.resizeWindow(window_name, 960, 540) cv2.imshow(window_name, read) # コールバックの設定 mouseData = mouseParam(window_name) # position = set() position = 0 while True: cv2.waitKey(1) # 左クリックがあったら表示 if mouseData.getEvent() == cv2.EVENT_LBUTTONDOWN: pos = mouseData.getPos() position = pos # 右クリックがあったら終了 elif mouseData.getEvent() == cv2.EVENT_RBUTTONDOWN: break
import freenect import cv2 import numpy as np from functions import * def nothing(x): pass #cv2.namedWindow('edge') cv2.namedWindow('Video') cv2.moveWindow('Video', 5, 5) cv2.namedWindow('Navig', cv2.WINDOW_AUTOSIZE) cv2.resizeWindow('Navig', 400, 100) cv2.moveWindow('Navig', 700, 5) #cv2.namedWindow('Fin') #cv2.namedWindow('Win') kernel = np.ones((5, 5), np.uint8) print('Press ESC in window to stop') cv2.createTrackbar('val1', 'Video', 37, 1000, nothing) cv2.createTrackbar('val2', 'Video', 43, 1000, nothing) cv2.createTrackbar('bin', 'Video', 20, 50, nothing) cv2.createTrackbar('erode', 'Video', 4, 10, nothing) #after plenty of testing imn = cv2.imread('blank.bmp') im0 = cv2.imread("Collision Alert.bmp") im1 = cv2.imread("VCP Reverse.bmp") #cv2.createTrackbar('dilate', 'edge',0,10,nothing)
import numpy as np from nms import non_max_suppression_fast # HOG parametrization # --- code here --- # Define HOG descriptor # --- code here --- # Load the classifier stored in the pickle model # --- code here --- # Define image and Window size image = cv2.imread() # --- code here --- cv2.namedWindow('Sliding Window', cv2.WINDOW_NORMAL) cv2.resizeWindow('Sliding Window', image.shape[1] / 2, image.shape[0] / 2) # Image pyramid parameters scale = 0.0 # --- code here --- minSize = (0, 0) # --- code here --- # Sliding window parameters stepSize = 0 # --- code here --- (winW, winH) = (0, 0) # --- code here --- bboxes = np.zeros(4, np.int64) # Variable to save the resulting bounding boxes # loop over the image pyramid for i, resized in enumerate(pyramid(image, scale=scale, minSize=minSize)): # loop over the sliding window for each layer of the pyramid for (x, y, window) in sliding_window(resized, stepSize=stepSize, windowSize=(winW, winH)):
cv2.destroyAllWindows() # Load ORB, BF and model objects orb = cv2.ORB_create() bf = cv2.BFMatcher(cv2.NORM_HAMMING2, crossCheck=True) model = cv2.imread('./../index0_s.jpg') # Detect and compute keypoints kp_model, des_model = orb.detectAndCompute(model, None) try: # Initialize camera cap = cv2.VideoCapture(0) cv2.namedWindow('Result', cv2.WINDOW_NORMAL) cv2.resizeWindow('Result', 640, 480) while True: ret, frame = cap.read() # frame = cv2.flip(frame, 1) kp_frame, des_frame = orb.detectAndCompute(frame, None) matches = bf.match(des_model, des_frame) good = [] for index, m in enumerate(matches): if index < len(matches) - 1 and m.distance < 0.75 * matches[ index + 1].distance: good.append(m) if len(good) < 5: # print(len(good)) cv2.imshow("Result", frame) k = cv2.waitKey(1)
def open_window(width, height): cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL) cv2.resizeWindow(WINDOW_NAME, width, height) cv2.moveWindow(WINDOW_NAME, 0, 0) cv2.setWindowTitle(WINDOW_NAME, 'Camera Demo for Jetson TX2/TX1')
def imshow(img, name, scale): cv2.namedWindow(name, cv2.WINDOW_NORMAL) cv2.resizeWindow(name, *scale) cv2.imshow(name, img) cv2.waitKey(0)
def capture_images(ges_name): create_folder(str(ges_name)) #video capturing cam = cv2.VideoCapture(0) cv2.namedWindow("test") img_counter = 0 t_counter = 1 training_set_image_name = 1 test_set_image_name = 1 listImage = [1, 2, 3, 4, 5] #trackbar creation cv2.namedWindow("Trackbars") cv2.createTrackbar("L - H", "Trackbars", 0, 179, nothing) cv2.createTrackbar("L - S", "Trackbars", 0, 255, nothing) cv2.createTrackbar("L - V", "Trackbars", 0, 255, nothing) cv2.createTrackbar("U - H", "Trackbars", 179, 179, nothing) cv2.createTrackbar("U - S", "Trackbars", 255, 255, nothing) cv2.createTrackbar("U - V", "Trackbars", 255, 255, nothing) cv2.resizeWindow('Trackbars', 300, 80) for loop in listImage: while True: #frame reading ret, frame = cam.read() frame = cv2.flip(frame, 1) l_h = cv2.getTrackbarPos("L - H", "Trackbars") l_s = cv2.getTrackbarPos("L - S", "Trackbars") l_v = cv2.getTrackbarPos("L - V", "Trackbars") u_h = cv2.getTrackbarPos("U - H", "Trackbars") u_s = cv2.getTrackbarPos("U - S", "Trackbars") u_v = cv2.getTrackbarPos("U - V", "Trackbars") img = cv2.rectangle(frame, (425, 100), (625, 300), (0, 255, 0), thickness=2, lineType=8, shift=0) lower_blue = np.array([l_h, l_s, l_v]) upper_blue = np.array([u_h, u_s, u_v]) imcrop = img[102:298, 427:623] #adjusting the image contrast thresholds #Colour convertion hsv = cv2.cvtColor(imcrop, cv2.COLOR_BGR2HSV) #mask creation mask = cv2.inRange(hsv, lower_blue, upper_blue) #binary otsu,blob analysis #when it becomes blacka nd white,the noises will be automatically removed result = cv2.bitwise_and(imcrop, imcrop, mask=mask) cv2.putText(frame, str(img_counter), (30, 400), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (127, 127, 255)) cv2.imshow("test", frame) cv2.imshow("mask", mask) cv2.imshow("result", result) if cv2.waitKey(1) == ord('c'): #saving if t_counter <= 350: img_name = "./mydata/training_set/" + str( ges_name) + "/{}.png".format(training_set_image_name) #image scaling save_img = cv2.resize(mask, (image_x, image_y)) cv2.imwrite(img_name, save_img) print("{} written!".format(img_name)) training_set_image_name += 1 if t_counter > 350 and t_counter <= 400: img_name = "./mydata/test_set/" + str( ges_name) + "/{}.png".format(test_set_image_name) save_img = cv2.resize(mask, (image_x, image_y)) cv2.imwrite(img_name, save_img) print("{} written!".format(img_name)) test_set_image_name += 1 if test_set_image_name > 250: break t_counter += 1 if t_counter == 401: t_counter = 1 img_counter += 1 elif cv2.waitKey(1) == 27: break if test_set_image_name > 250: break cam.release() cv2.destroyAllWindows()
def nothing(x): i = 0 import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('C:/Users/ashwi/Desktop/opencv/opencv.png') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.resizeWindow('image', 1000, 1000) cv2.createTrackbar('Blur', 'image', 5, 200, nothing) while True: n = cv2.getTrackbarPos('Blur', 'image') if (n > 1): kernel = np.ones((n, n), np.float32) / (n * n) dst = cv2.filter2D(img, -1, kernel) cv2.imshow('image', dst) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows()
# '''Detection of color in images''' import cv2 import numpy as np #Dummy Function def empty(a): pass # Creating TrakcBar to get the desired color we want cv2.namedWindow("TrackBars") cv2.resizeWindow("TrackBars", 640,240) cv2.createTrackbar("Hue Min", "TrackBars", 0, 179, empty) cv2.createTrackbar("Hue Max", "TrackBars", 19, 179, empty) cv2.createTrackbar("Sat Min", "TrackBars", 110, 255, empty) cv2.createTrackbar("Sat Max", "TrackBars", 240, 255, empty) cv2.createTrackbar("Val Min", "TrackBars", 150, 255, empty) cv2.createTrackbar("Val Max", "TrackBars", 255, 255, empty) while True: img = cv2.imread("Resources/lambo.PNG") #converting image to HSV format 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")
# define display window names window_nameL = "LEFT Camera Input" # window name window_nameR = "RIGHT Camera Input" # window name # create window by name (as resizable) cv2.namedWindow(window_nameL, cv2.WINDOW_NORMAL) cv2.namedWindow(window_nameR, cv2.WINDOW_NORMAL) # set sizes and set windows frameL, frameR = stereo_camera.get_frames() height, width, channels = frameL.shape cv2.resizeWindow(window_nameL, width, height) height, width, channels = frameR.shape cv2.resizeWindow(window_nameR, width, height) # controls print("s : swap cameras left and right") print("e : export camera calibration to file") print("l : load camera calibration from file") print("x : exit") print() print("space : continue to next stage") print() while (keep_processing):
def show(img, name="z"): cv2.namedWindow(name, cv2.WINDOW_NORMAL) cv2.resizeWindow(name, 600, 600) cv2.imshow(name, img) k = cv2.waitKey(0) # 0==wait forever
import numpy as np frameWidth = 640 frameHeight = 480 cap = cv2.VideoCapture(0) cap.set(3, frameWidth) cap.set(4, frameHeight) cap.set(10, 150) def empty(a): pass cv2.namedWindow("HSV") cv2.resizeWindow("HSV", 640, 240) cv2.createTrackbar("HUE Min", "HSV", 48, 179, empty) cv2.createTrackbar("HUE Max", "HSV", 98, 179, empty) cv2.createTrackbar("SAT Min", "HSV", 31, 255, empty) cv2.createTrackbar("SAT Max", "HSV", 140, 255, empty) cv2.createTrackbar("VALUE Min", "HSV", 9, 255, empty) cv2.createTrackbar("VALUE 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")
# -*- coding: utf-8 -*- import cv2 frame = cv2.imread("Lane1-p1-ref.png") fgbg = cv2.createBackgroundSubtractorMOG2(history=1000, varThreshold=16, detectShadows=True) fgmask = fgbg.apply(frame) cv2.namedWindow('frame', cv2.WINDOW_NORMAL) cv2.resizeWindow('frame', 640, 800) cv2.imshow('frame', fgmask) cv2.waitKey(0)
import cv2 import numpy as np img = cv2.imread('images/baboon1.png') blues = img[0, 0, 0] greens = img[:, :, 1] reds = img[:, :, 2] cv2.namedWindow("image", cv2.WINDOW_NORMAL) cv2.resizeWindow('image', 600, 600) cv2.namedWindow("greens", cv2.WINDOW_NORMAL) cv2.resizeWindow('greens', 600, 600) cv2.namedWindow("reds", cv2.WINDOW_NORMAL) cv2.resizeWindow('reds', 600, 600) # Saving an Image on a key press cv2.imshow('image', blues) cv2.imshow('greens', greens) cv2.imshow('reds', reds) print("press 's' to save the image as 'image_test_2.png\n") key = cv2.waitKey( 0 ) & 0xFF # NOTE: if you are using a 64-bit machine,this needs to be: key = cv2.waitKey(0) & 0xFF if key == 27: # wait for the ESC key to exit cv2.destroyAllWindows() elif key == ord('s'): # wait for 's' key to save and exit cv2.imwrite('image_test_2.png', img) cv2.destroyAllWindows()
def scatteredInterpolantCalibrationTrack(videosFilePath, videoNames, startFrame, endFrame): right_clicks = [] def mouse_callback(event, x, y, flags, params): #right-click event value is 2 if event == 2: #store the coordinates of the right-click event right_clicks.append([x, y]) #this just verifies that the mouse data is being collected #you probably want to remove this later print(right_clicks) kernelOpen = np.ones((5, 5)) kernelClose = np.ones((20, 20)) #Open a vidcap for each video worldVidCap = cv2.VideoCapture(videosFilePath + '/' + videoNames[0] + '_f_c.mp4') eye0VidCap = cv2.VideoCapture(videosFilePath + '/' + videoNames[1] + '_f_c.mp4') eye1VidCap = cv2.VideoCapture(videosFilePath + '/' + videoNames[2] + '_f_c.mp4') #Get frame count frame_count = int(worldVidCap.get(cv2.CAP_PROP_FRAME_COUNT)) vidWidth = worldVidCap.get(cv2.CAP_PROP_FRAME_WIDTH) #Get video height vidHeight = worldVidCap.get(cv2.CAP_PROP_FRAME_HEIGHT) #Get video width vidLength = range(frame_count) outputVid = cv2.VideoWriter(videosFilePath + '/Calibration.mp4', -1, 30, (int(vidWidth), int(vidHeight))) #Set HSV value (Hue, Saturation, Brightness) for color of ball lowerBound = np.array([160, 135, 135]) upperBound = np.array([180, 250, 250]) #Set an array for the calibration point calibPointXY = np.zeros(((endFrame - startFrame), 2)) for jj in vidLength: #For the length of the video if jj < startFrame: #If frame is before the start of calibration dont do anything success, image = worldVidCap.read() #reads in frame continue elif jj >= endFrame: #If frame is after calibration end the for loop break else: #If frame is in calibration range success, image = worldVidCap.read() #reads in frame #convert BGR to HSV imgHSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) mask = cv2.inRange(imgHSV, lowerBound, upperBound) #Clean up stray dots and fill in gaps maskOpen = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernelOpen) maskClose = cv2.morphologyEx(maskOpen, cv2.MORPH_CLOSE, kernelClose) #Draw a contour with mask maskFinal = maskClose conts, h = cv2.findContours(maskFinal.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) k = 0 objInFrame = [] if jj == startFrame: #point = plt.ginput(n=1, show_clicks = True) #plt.imshow(image) scale_width = 640 / image.shape[1] scale_height = 480 / image.shape[0] scale = min(scale_width, scale_height) window_width = int(image.shape[1] * scale) window_height = int(image.shape[0] * scale) cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.resizeWindow('image', window_width, window_height) cv2.setMouseCallback('image', mouse_callback) cv2.imshow('image', image) cv2.waitKey(0) print(right_clicks) point = right_clicks[0] normPoint = np.sqrt((point[0]**2 + point[1]**2)) diffFromPointtoCont = 1000000 for ii in range(len(conts)): center, radius = cv2.minEnclosingCircle(conts[ii]) normCenter = np.sqrt(int(center[0])**2 + int(center[1])**2) if abs(normCenter - normPoint) < diffFromPointtoCont: diffFromPointtoCont = abs(normCenter - normPoint) contIndex = ii centerPoint = normCenter objInFrame.append(jj) else: #If contour is detected(Object is in frame) conts is true #Loop to output center position #for i in range(len(conts)): diffCenter = 100000000000 diffRadius = 100000000000 for i in range(len(conts)): center, radius = cv2.minEnclosingCircle(conts[i]) centerx = int(center[0]) centery = int(center[1]) newNormCenter = np.sqrt(centerx**2 + centery**2) radiusChange = abs(radius - radiusFromLastFrame) #print(radiusChange,'RadiusChange') #if abs(newNormCenter - centerPoint) < diffCenter and abs(newNormCenter - centerPoint) <30 and radiusChange <diffRadius: if abs( newNormCenter - centerPoint ) < 60 and radiusChange < diffRadius and radius > 35: diffCenter = abs(newNormCenter - centerPoint) diffRadius = radiusChange #print(diffRadius,'DiffRadius') calibPointXY[(jj - startFrame), 0] = centerx calibPointXY[(jj - startFrame), 1] = centery contIndex = i #print(diffCenter) objInFrame.append(i) #print('NEW FRAME') if len(objInFrame) > 0: center, radius = cv2.minEnclosingCircle(conts[contIndex]) centerPoint = np.sqrt(int(center[0])**2 + int(center[1])**2) radiusFromLastFrame = radius calibCont = conts[contIndex] cv2.drawContours(image, calibCont, -1, (255, 0, 0), 3) cv2.imshow('im', image) cv2.waitKey(200) np.save(videosFilePath + '/CalibLocXY.npy', calibPointXY) worldVidCap.release() #Reset worldVidcap worldVidCap = cv2.VideoCapture(videosFilePath + '/' + videoNames[0] + '_f_c.mp4') #Plot the points of the ball from the last six frames for jj in vidLength: #For the length of the video if jj < startFrame: #If frame is before the start of calibration dont do anything success, image = worldVidCap.read() continue elif jj >= endFrame: #If frame is after calibration end the for loop break else: #If frame is in calibration range success, image = worldVidCap.read() #Make the pixel of the center point red cv2.circle(image, (int(calibPointXY[(jj - startFrame), 0]), int(calibPointXY[int(jj - startFrame), 1])), radius=3, color=[255, 0, 0], thickness=-1) #image[int(calibPointXY[int(jj-startFrame),1]),int(calibPointXY[int(jj-startFrame),0]),:] = [0,0,255] if (jj - startFrame) > 1: #Make the pixel of the center point of a previous frame red #image[int(calibPointXY[((jj-1)-startFrame),1]),int(calibPointXY[((jj-1)-startFrame),0]),:] = [0,0,255] cv2.circle(image, (int(calibPointXY[int((jj - 1) - startFrame), 0]), int(calibPointXY[int((jj - 1) - startFrame), 1])), radius=3, color=[255, 0, 0], thickness=-1) if (jj - startFrame) > 2: #Make the pixel of the center point of a previous frame red #image[int(calibPointXY[((jj-2)-startFrame),1]),int(calibPointXY[((jj-2)-startFrame),0]),:] = [0,0,255] cv2.circle(image, (int(calibPointXY[int((jj - 2) - startFrame), 0]), int(calibPointXY[int((jj - 2) - startFrame), 1])), radius=3, color=[255, 0, 0], thickness=-1) if (jj - startFrame) > 3: #Make the pixel of the center point of a previous frame red #image[int(calibPointXY[((jj-3)-startFrame),1]),int(calibPointXY[((jj-3)-startFrame),0]),:] = [0,0,255] cv2.circle(image, (int(calibPointXY[int((jj - 3) - startFrame), 0]), int(calibPointXY[int((jj - 3) - startFrame), 1])), radius=3, color=[255, 0, 0], thickness=-1) if (jj - startFrame) > 4: #Make the pixel of the center point of a previous frame red #image[int(calibPointXY[((jj-4)-startFrame),1]),int(calibPointXY[((jj-4)-startFrame),0]),:] = [0,0,255] cv2.circle(image, (int(calibPointXY[int((jj - 4) - startFrame), 0]), int(calibPointXY[int((jj - 4) - startFrame), 1])), radius=3, color=[255, 0, 0], thickness=-1) if (jj - startFrame) > 5: #Make the pixel of the center point of a previous frame red #image[int(calibPointXY[((jj-5)-startFrame),1]),int(calibPointXY[((jj-5)-startFrame),0]),:] = [0,0,255] cv2.circle(image, (int(calibPointXY[int((jj - 5) - startFrame), 0]), int(calibPointXY[int((jj - 5) - startFrame), 1])), radius=3, color=[255, 0, 0], thickness=-1) if (jj - startFrame) > 6: #Make the pixel of the center point of a previous frame red #image[int(calibPointXY[((jj-6)-startFrame),1]),int(calibPointXY[((jj-6)-startFrame),0]),:] = [0,0,255] cv2.circle(image, (int(calibPointXY[int((jj - 6) - startFrame), 0]), int(calibPointXY[int((jj - 6) - startFrame), 1])), radius=3, color=[255, 0, 0], thickness=-1) #cv2.imshow('im',image) #cv2.waitKey(200) outputVid.write(image) outputVid.release() #plt.imshow(image) #calibCorners = plt.ginput(4) #imgGrey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #points = cv2.cornerEigenValsAndVecs(imgGrey,calibCorners) return calibPointXY
def showImage(image, title): cv2.namedWindow(title, cv2.WINDOW_NORMAL) cv2.resizeWindow(title, 1200, 1800) cv2.imshow(title, image) cv2.waitKey() cv2.destroyAllWindows()
def __init__(self, image, params_filename): # Takes a single image and a .pkl file of parameters # Save a copy of the original image for display self.orig_image = image self.image = image #print("orig ", image.shape) # Stash dimensions of original image h, w = image.shape[:2] self.orig_image_size = (w, h) # Stash the filename where we will save parameters self.params_filename = params_filename # Convert to greyscale for thresholding self.gr_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #print("grey ", self.gr_image.shape) # Blur to reduce effect of noise self.gr_image = cv2.GaussianBlur(self.gr_image, (9, 9), 0) #print("blur", self.gr_image.shape) #cv2.imwrite("gr_only.png", self.gr_image) # See if we can retrieve presets from prexisting file # Otherwise, use default parameters try: with open(self.params_filename, "rb") as f: self.params = pickle.load(f) #print(self.params_filename) #print(self.params) except: self.params = ThresholdParams( erased_mask=np.ones_like(self.gr_image)) #print('erased ', np.ones_like(self.gr_image).shape) #print("here") self.gr_image_scaled = normalize_img(self.gr_image, self.params) _, self.mask_image = apply_mask(self.gr_image_scaled, self.params) self.update_mask = False image_area = self.orig_image_size[0] * self.orig_image_size[1] self.trackbar_window = 'Parameters' cv2.namedWindow(self.trackbar_window) cv2.resizeWindow(self.trackbar_window, 600, 280) cv2.createTrackbar("Max Saturation", self.trackbar_window, self.params.max_sat, 255, self.on_sat_change) cv2.createTrackbar("Min Saturation", self.trackbar_window, self.params.min_sat, 255, self.on_sat_change) #TODO what if min>max cv2.createTrackbar("threshold", self.trackbar_window, self.params.threshold, 255, self.on_slider_change) cv2.createTrackbar("morph_x", self.trackbar_window, self.params.morph_x, 25, self.on_slider_change) cv2.createTrackbar("morph_y", self.trackbar_window, self.params.morph_y, 25, self.on_slider_change) cv2.createTrackbar("Min Size", self.trackbar_window, self.params.min_contour_area, 5000, self.on_slider_change) cv2.createTrackbar("Max Size", self.trackbar_window, self.params.max_contour_area, 20000, self.on_slider_change) cv2.createTrackbar("contour_aspect", self.trackbar_window, int(self.params.min_contour_aspect * 100), 300, self.on_slider_change) # Determine minimum scaling factor of image fy = MAX_HEIGHT / float(h) fx = MAX_WIDTH / float(w) self.zoom = min(1.0, min(fx, fy)) self.min_zoom = self.zoom # Set display size to scaled dimensions self.display_size = (int(round(w * self.zoom)), int(round(h * self.zoom))) # Initialize current scroll offset to 0, 0 self.scroll_offset = np.array([0., 0.]) # Transform the image to get ready for display self.transform_image() # Set up some internal flags for mouse interactions self.is_modified = False self.mouse_active = True self.dragging = False self.brush_size = 200 # Create a window with OpenCV self.window = 'Visualize Mask' cv2.namedWindow(self.window) # Tell OpenCV we want mouse events cv2.setMouseCallback(self.window, self.mouse, self)
import cv2 cam = cv2.VideoCapture(0, cv2.CAP_DSHOW) cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1280.0) cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 720.0) cv2.namedWindow("test") cv2.resizeWindow('test', 1280, 720) img_counter = 0 while True: ret, frame = cam.read() cv2.imshow("test", frame) if not ret: break k = cv2.waitKey(1) if k % 256 == 27: # ESC pressed print("Escape hit, closing...") break elif k % 256 == 32: # SPACE pressed img_name = "opencv_frame_{}.png".format(img_counter) cv2.imwrite(img_name, frame) print("{} written!".format(img_name)) img_counter += 1 cam.release()
def draw_projected_pointclouds_at_a_frame(basedir, capture_date, frame_id, track_ids=None, track_id_to_color_map=None, window_name=None, savedir=None): # load a point cloud of the entire scene at this frame pcd = dl.load_a_pointcloud(basedir, capture_date, frame_id) # project the points w, h = 1000, 750 image = np.zeros((h, w, 3), dtype=np.uint8) def _project_points(v): nv = v.shape[0] R = np.array([[0.13637362, -0.98993436, -0.03784438], [-0.91489993, -0.1405043, 0.37843977], [-0.37994783, -0.01698538, -0.92485196]]) T = np.array([0.0, -27, -80]) D = np.array([0, 0, 0, 0, 0.]) _w, _h = w / 2, h / 2 K = np.array([[-2 * _w, 0.0, _w], [0., 2 * _h, _h], [0, 0, 1.]]) return cv2.projectPoints(v, R, T, K, D)[0].reshape(nv, 2).astype('int') mask = (pcd[:, 0] != np.inf) & (pcd[:, 2] > -5.) v_I = _project_points(pcd[mask, :]) u, v = v_I[:, 0], v_I[:, 1] mask = (u >= 0) & (v >= 0) & (u < w) & (v < h) ids = (np.concatenate([v[mask], v[mask], v[mask]]), np.concatenate([u[mask], u[mask], u[mask]]), np.repeat([0, 1, 2], np.sum(mask))) image[ids] = 255 # load instance-wise segmented point clouds if track_id_to_color_map is None: track_id_to_color_map = {} pcds = dl.load_pointclouds_at_a_frame(basedir, capture_date, frame_id, track_ids) for tid, pcd in pcds.items(): if tid not in track_id_to_color_map.keys(): track_id_to_color_map[tid] = generate_a_random_color(np.uint8) color = track_id_to_color_map[tid] v_I = _project_points(pcd) u, v = v_I[:, 0], v_I[:, 1] mask = (u >= 0) & (v >= 0) & (u < w) & (v < h) ones = np.ones(np.sum(mask), dtype=int) image[(v[mask], u[mask], ones * 0)] = color[0] image[(v[mask], u[mask], ones * 1)] = color[1] image[(v[mask], u[mask], ones * 2)] = color[2] text_str = '{:07d}'.format(frame_id) image = draw_a_text_box(image, text_str, (50, 50), (200, 120, 150.), 1, 2, noise=False) if window_name is not None: cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(window_name, 800, 800) cv2.moveWindow(window_name, 0, 0) cv2.imshow(window_name, image) cv2.waitKey(0) if savedir is not None: frame_key = '{}_{:07d}'.format(capture_date, frame_id) fn_save = os.path.join(savedir, capture_date, '{}.png'.format(frame_key)) if not os.path.exists(os.path.dirname(fn_save)): os.makedirs(os.path.dirname(fn_save), exist_ok=True) cv2.imwrite(fn_save, image) print('{} saved.'.format(fn_save)) return image, track_id_to_color_map
Himg_thr_er_im, Himg_thr_kpoints = structural.blob_detection_watershed( uHEt, pow(2, extract_level), None, area_low=area_low) structural_features.update( structural.he_structural_features( uH, uE, uR, prefix="L{}_".format(level_prefix), subdivision=(4, 4))) if show_intermediate: cv2.namedWindow("Channel Separation", cv2.WINDOW_NORMAL) cv2.resizeWindow("Channel Separation", 1400, 900) cv2.imshow( "Channel Separation", np.hstack([ orig_patch, cv2.cvtColor(uH, cv2.COLOR_GRAY2RGB), cv2.cvtColor(uE, cv2.COLOR_GRAY2RGB), cv2.cvtColor(uR, cv2.COLOR_GRAY2RGB), ])) rv = cv2.waitKey(8000) cv2.destroyAllWindows() subpatch_nuclei = list() for ii in range(4): for jj in range(4): subpatch_nuclei.append(
ww = int(spb[0] * t_size / 300) www = int((w + 10) * t_size / 100) www_s = int((w + 20) * t_size / 100) * 2 / 5 cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), ww) cv2.putText(img, emo, (x + 2, y + h - 2), cv2.FONT_HERSHEY_SIMPLEX, www_s, (255, 0, 255), thickness=www, lineType=1) # img_gray full face face_img_gray part of face if face_exists: cv2.HoughLinesP cv2.namedWindow(emo, 0) cent = int((height * 1.0 / width) * size) cv2.resizeWindow(emo, (size, cent)) cv2.imshow(emo, img) k = cv2.waitKey(0) cv2.destroyAllWindows() if k & 0xFF == ord('q'): break elif flag == 1: img = cv2.imread(image) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) results = predict_emotion(img_gray) # face_img_gray result_sum = np.array([0] * num_class) for result in results: result_sum = result_sum + np.array(result) print(result) angry, disgust, fear, happy, sad, surprise, neutral = result_sum # 输出所有情绪的概率
def draw_2d_labels_at_an_image(basedir, capture_date, camera_name, frame_id, track_ids=None, labels=None, track_id_to_color_map=None, window_name=None, savedir=None): if labels is None: labels = dl.load_label_2d_at_an_image(basedir, capture_date, camera_name, frame_id, track_ids) image = dl.load_an_image(basedir, capture_date, camera_name, frame_id) if track_id_to_color_map is None: track_id_to_color_map = {} for k, d in labels.items(): tid = d['tracking_id'] assert k == tid, '>> Draw_2d_labels_at_an_image :: Invalid label: {}_{}_{:07d}'.format( capture_date, camera_name, frame_id) # assign a color to the instance if tid not in track_id_to_color_map.keys(): track_id_to_color_map[tid] = generate_a_random_color(np.uint8) color = track_id_to_color_map[tid] # draw labels text_loc = None if 'polygon' in d.keys(): if d['polygon'] is not None: polygon = np.array(d['polygon']) image = draw_a_polygon(image, polygon, color) text_loc = tuple(np.min(polygon, axis=0)) if d['category'] == 'pedestrian': text_str = tid[-4:] if d['keypoint'] is not None: # image = draw_a_skeleton(image, keypoints) if text_loc is None: pts = [[v['x'], v['y']] for v in d['keypoint'].values()] text_loc = tuple(np.min(kpts, axis=0)) elif d['category'] == 'vehicle': subtype = d['subtype'] if 'subtype' in d.keys() else None text_str = '{}|{}'.format(tid[-4:], subtype) print('drawing vehicle not implemented yet') image = draw_a_text_box(image, text_str, text_loc, color) if window_name is not None: cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(window_name, 800, 800) cv2.moveWindow(window_name, 0, 0) cv2.imshow(window_name, image) cv2.waitKey(0) if savedir is not None: frame_key = '{}_{}_{:07d}'.format(capture_date, camera_name, frame_id) fn_save = os.path.join(savedir, capture_date, camera_name, '{}.png'.format(frame_key)) if not os.path.exists(os.path.dirname(fn_save)): os.makedirs(os.path.dirname(fn_save), exist_ok=True) cv2.imwrite(fn_save, image) print('{} saved.'.format(fn_save)) return image, track_id_to_color_map
import cv2 import numpy as np def threshBar(x): pass img = cv2.imread('E:\\OpenCV\\py_version\\demo\\venv\\Picture\\IMG_8881.jpg') grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 适当缩小窗口 cv2.namedWindow('Thresh Window', cv2.WINDOW_NORMAL) cv2.namedWindow('AdaptiveThresh Window', cv2.WINDOW_NORMAL) cv2.namedWindow('BGR Thresh Window', cv2.WINDOW_NORMAL) cv2.resizeWindow('Thresh Window', 640, 480) cv2.resizeWindow('AdaptiveThresh Window', 640, 480) cv2.resizeWindow('BGR Thresh Window', 640, 480) ret, threshImg = cv2.threshold(grayImg, 122, 255, cv2.THRESH_BINARY) ret, bgrThreshImg = cv2.threshold(img, 122, 255, cv2.THRESH_BINARY) adaptiveThreshImg = cv2.adaptiveThreshold(grayImg, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 49, 0) cv2.imshow('AdaptiveThresh Window', adaptiveThreshImg) cv2.imshow('Thresh Window', threshImg) cv2.imshow('BGR Thresh Window', bgrThreshImg) cv2.waitKey() cv2.destroyAllWindows()
def grab_and_send(self): if (not self.cap.isOpened()): print("Error in video file path") pcd = o3d.geometry.PointCloud() while (self.cap.isOpened()): ret, frame = self.cap.read() if (ret): pcd.clear() split_width = frame.shape[1] // 2 left_img, right_img = frame[:, 0: split_width, :], frame[:, split_width - 1:-1, :] rgb_img = left_img #thresholding for detecting vessels left_img_alt = cv2.adaptiveThreshold( cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 3) left_img = cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY) right_img_alt = cv2.adaptiveThreshold( cv2.cvtColor(right_img, cv2.COLOR_BGR2GRAY), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 3) right_img = cv2.cvtColor(right_img, cv2.COLOR_BGR2GRAY) #use SGBM block matching algorithm l_stereo = cv2.StereoSGBM_create( numDisparities=16, blockSize=3, uniquenessRatio=15, speckleWindowSize=0, speckleRange=2, preFilterCap=63, mode=cv2.STEREO_SGBM_MODE_SGBM_3WAY) r_stereo = cv2.ximgproc.createRightMatcher(l_stereo) wls_filter = cv2.ximgproc.createDisparityWLSFilter( matcher_left=l_stereo) wls_filter.setLambda(l) wls_filter.setSigmaColor(sigma) d_l = l_stereo.compute(left_img, right_img) d_r = r_stereo.compute(right_img, left_img) d_l = np.int16(d_l) d_r = np.int16(d_r) filtered = wls_filter.filter(d_l, left_img, None, d_r) filtered = cv2.normalize(src=filtered, dst=filtered, beta=0, alpha=255, norm_type=cv2.NORM_MINMAX) filtered = np.uint8(filtered) if (self.first): self.prev = filtered self.first = False else: filtered = (filtered + self.prev) / 2 self.prev = filtered filtered = np.uint8(filtered) rgb_img1 = o3d.geometry.Image(rgb_img) filtered_o3d = o3d.geometry.Image(filtered) rgbd_img = o3d.geometry.RGBDImage.create_from_color_and_depth( rgb_img1, filtered_o3d) pcd = o3d.geometry.PointCloud.create_from_rgbd_image( rgbd_img, o3d.camera.PinholeCameraIntrinsic( o3d.camera.PinholeCameraIntrinsicParameters. PrimeSenseDefault)) #flip to proper frame flip_transform = [[1, 0, 0, -.0005], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] pcd.transform(flip_transform) # cl, ind = pcd.remove_statistical_outlier(nb_neighbors=15, # std_ratio=5.0) # inlier_cloud = pcd.select_down_sample(ind) self.viz.add_geometry(pcd) self.viz.update_geometry() self.viz.poll_events() self.viz.update_renderer() cv2.namedWindow("Disparity", cv2.WINDOW_NORMAL) cv2.resizeWindow("Disparity", 800, 800) cv2.imshow("Left_alt", left_img_alt) cv2.imshow("Right_alt", right_img_alt) cv2.imshow("Unaltered", rgb_img) cv2.imshow("Disparity", filtered) #o3d.visualization.draw_geometries([pcd]) cv2.waitKey(50) cv2.destroyAllWindows() return
def show_cv(img, name='image'): cv2.namedWindow(name, cv2.WINDOW_NORMAL) cv2.resizeWindow(name, 600, 400) cv2.imshow(name, img) cv2.waitKey() cv2.destroyWindow(name)
# If found, add object points, image points (afte refining them) if ret == True: print('Chess board pattern found') objpoints.append(objp) corners2 = cv2.cornerSubPix(binary, corners, (11,11), (-1,-1), criteria) imgpoints.append(corners2) # Draw and display the corners img = cv2.drawChessboardCorners(img, (cbcol,cbrow), corners2, ret) # cv2.imwrite(image_folder +'/detected_corners/" + fname + "_chess.jpg", img) # Save image # Make window and show image frame_name = 'detected chessboard' cv2.namedWindow(frame_name, cv2.WINDOW_NORMAL) cv2.resizeWindow(frame_name, 1920,1080) cv2.imshow(frame_name, img) cv2.waitKey(250) retval, cameraMatrix, distCoeffs, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None, criteria=criteria) cv2.destroyAllWindows() mean_error = 0 # Reprojection error, should be as close to zero as possible for i in xrange(len(objpoints)): imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], cameraMatrix, distCoeffs) error = cv2.norm(imgpoints[i], imgpoints2, cv2.NORM_L2)/len(imgpoints2) mean_error += error print( "total error: {}".format(mean_error/len(objpoints)) ) if save_params: cal = [cameraMatrix, distCoeffs]
def readCSV(filename): allImages = list() colors = [(0, 0, 255), (255, 0, 0), (0, 255, 0), (255, 255, 0), (255, 0, 255), (0, 255, 255), (128, 0, 128)] lines = None try: with open(filename, 'r') as f: lines = f.readlines()[1:] # Starts reading from second line except Exception as e: print("\n\nFile not found") print( "Please place your file in the same directory or provide an absolute path" ) print( "In the event you're using data.csv, please place it in the same directory as this program file" ) exit(0) loopIndex = 0 activeState = True while activeState: # Get current image currLine = lines[loopIndex] tokens = currLine.strip().split(",") fileName = tokens[0] image = cv2.imread('input/' + fileName) # Get each region regions = [] end = 1 for i in range(7): start = end end = start + 9 midList = list(map(int, tokens[start:end])) regions.append(midList) end += 7 # Draw polygons if image is not None: for i, region in enumerate(regions): if region[0] == 1: # coords = np.array([[region[1],region[2]],[region[3],region[4]],[region[5],region[6]],[region[7],region[8]]]) coords = np.array([[region[i], region[i + 1]] for i in range(1, 9, 2)]) coords = coords.reshape((-1, 1, 2)) image = cv2.polylines(image, [coords], True, colors[i], 3) cv2.namedWindow(fileName, cv2.WINDOW_NORMAL) cv2.resizeWindow(fileName, (2000, 2000)) cv2.imshow(fileName, image) cv2.waitKey(0) try: if keyboard.is_pressed('q'): activeState = False if keyboard.is_pressed('d'): loopIndex = 0 if loopIndex == len(lines) - 1 else (loopIndex + 1) if keyboard.is_pressed('a'): loopIndex = len(lines) - 1 if loopIndex == 0 else (loopIndex - 1) cv2.destroyAllWindows() except Exception as e: print("Error") break return
import numpy as np import MyOpenCVUtil as MyCV # create empty functions that do nothing, just to satisfied the cv2.trackbar parameter def empty(x): pass frameWidth = 640 frameHeight = 480 cap = cv2.VideoCapture(0) cv2.namedWindow("Parameters") cv2.resizeWindow("Parameters", 640, 240) cv2.createTrackbar("Threshold 1", "Parameters", 23, 255, empty) cv2.createTrackbar("Threshold 2", "Parameters", 20, 255, empty) # Create bounding area to detect real object (and eliminate noise object) # minimum value 5000 and max value to detect is 30000 cv2.createTrackbar("Area", "Parameters", 5000, 30000, empty) while True: _, img = cap.read() # copy the img variable image/video content to new variable named imgContour imgContour = img.copy() img = cv2.resize(img, (frameWidth, frameHeight)) # make image blurry (the (x,y) parameter must always be an ODD number, # more higher number= more blurry)
import pyautogui import cv2 import numpy as np resolution = (1920, 1000) codec = cv2.VideoWriter_fourcc(*"XVID") filename = "Recording.avi" fps = 60.0 out = cv2.VideoWriter(filename, codec, fps, resolution) cv2.namedWindow("Live", cv2.WINDOW_NORMAL) cv2.resizeWindow("Live", 480, 270) while True: img = pyautogui.screenshot() frame = np.array(img) frame = cv2.cvtColor(frame, cv2.COLOR_VGR2RGB) out.write(frame) cv2.imshow('Live', frame) if cv2.waitKey(1) == ord('q'): break out.release() cv2.destroyAllWindows
) if record: filename = time.strftime('%Y%m%d_%H%M%S_') + str(frame_idx) + '.jpg' cv2.imwrite(filename, frame) print('frame saved:', os.path.abspath(filename)) # Display the resulting frame if all(dim > 0 for dim in frame.shape): cv2.imshow('frame', frame) else: print('Empty frame!') continue if first_frame: cv2.resizeWindow('frame', frame.shape[1], frame.shape[0]) first_frame = False raw_key = cv2.waitKey(1) key = raw_key & 0xFF if key == ord('q'): break elif key == ord('f'): fullscreen = not fullscreen cv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, int(fullscreen)) elif key == ord('r'): reset() elif key == ord('b'): grayscale = not grayscale elif key == ord('g'):