Python cv2.HOUGH_GRADIENT Examples
The following are 23
code examples of cv2.HOUGH_GRADIENT().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cv2
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: detect_picture_color_circle.py From Python-Code with MIT License | 7 votes |
def findPiccircle(frame, color): hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) color_dict = color_list.getColorList() mask = cv2.inRange(hsv, color_dict[color][0], color_dict[color][1]) dilated = cv2.dilate(mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2) ## 需要修改minRadius以及maxRadius,用来限制识别圆的大小,排除其他的干扰 circles = cv2.HoughCircles(dilated, cv2.HOUGH_GRADIENT, 1, 1000, param1=15, param2=10, minRadius=15, maxRadius=50) center = None if circles is not None: x, y, radius = circles[0][0] center = (x, y) cv2.circle(frame, center, radius, (0, 255, 0), 2) cv2.circle(frame, center, 2, (0,255,0), -1, 8, 0 ); print('圆心:{}, {}'.format(x, y)) cv2.imshow('result', frame) if center != None: return center
Example #2
Source File: ImageMiniLab.py From ImageMiniLab with GNU General Public License v3.0 | 6 votes |
def hough_circles(self): src = self.cv_read_img(self.src_file) if src is None: return dst = cv.pyrMeanShiftFiltering(src, 10, 100) cimage = cv.cvtColor(dst, cv.COLOR_BGR2GRAY) circles = cv.HoughCircles(cimage, cv.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0, :]: cv.circle(src, (i[0], i[1]), i[2], (0, 0, 255), 2) cv.circle(src, (i[0], i[1]), 2, (255, 0, 255), 2) self.decode_and_show_dst(src) # 轮廓发现
Example #3
Source File: trainer_matches.py From Yugioh-bot with MIT License | 6 votes |
def capture_white_circles(self): self.prep_for_white_circles() img = cv2.cvtColor(self.white_query, cv2.COLOR_BGR2GRAY) img = cv2.medianBlur(img, 1) cimg = cv2.cvtColor(self.query, cv2.COLOR_BGR2RGB) circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, img.shape[0] / 15, param1=50, param2=22, minRadius=5, maxRadius=60) if circles is None: return circles = np.uint16(np.around(circles)) new_circles = [] for i in circles[0, :]: if self.in_box(i[0], i[1]) and not self.in_blacklist(i[0], i[1]): self.circlePoints.append((i[0], i[1])) new_circles.append(i) if self._debug: # self.draw_circles(circles, cimg) if len(new_circles) > 0: self.draw_circles(np.array([new_circles]), cimg)
Example #4
Source File: trainer_matches.py From Yugioh-bot with MIT License | 6 votes |
def read_captured_circles(self): img = cv2.cvtColor(self.query, cv2.COLOR_BGR2GRAY) img = cv2.medianBlur(img, 7) cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 30, param1=50, param2=30, minRadius=20, maxRadius=50) if circles is None: return circles = np.uint16(np.around(circles)) for i in circles[0, :]: if i[1] < 400: continue self.circlePoints.append((i[0], i[1])) if self._debug: self.draw_circles(circles, cimg)
Example #5
Source File: rpotter.py From rpotter with MIT License | 6 votes |
def FindWand(): global rval,old_frame,old_gray,p0,mask,color,ig,img,frame try: rval, old_frame = cam.read() cv2.flip(old_frame,1,old_frame) old_gray = cv2.cvtColor(old_frame,cv2.COLOR_BGR2GRAY) equalizeHist(old_gray) old_gray = GaussianBlur(old_gray,(9,9),1.5) dilate_kernel = np.ones(dilation_params, np.uint8) old_gray = cv2.dilate(old_gray, dilate_kernel, iterations=1) clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8)) old_gray = clahe.apply(old_gray) #TODO: trained image recognition p0 = cv2.HoughCircles(old_gray,cv2.HOUGH_GRADIENT,3,50,param1=240,param2=8,minRadius=4,maxRadius=15) if p0 is not None: p0.shape = (p0.shape[1], 1, p0.shape[2]) p0 = p0[:,:,0:2] mask = np.zeros_like(old_frame) ig = [[0] for x in range(20)] print "finding..." threading.Timer(3, FindWand).start() except: e = sys.exc_info()[1] print "Error: %s" % e exit
Example #6
Source File: Count_Coins.py From rpi-course with MIT License | 6 votes |
def CountCoins(img, cimg): circles = [] try: circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=0,maxRadius=0) except: circles = cv2.HoughCircles(img, cv.CV_HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0) if(circles is None): return circles = np.uint16(np.around(circles)) for i in circles[0, :]: # draw the outer circle cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) # draw the center of the circle cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
Example #7
Source File: Count_Coins.py From rpi-course with MIT License | 6 votes |
def CountCoins(img, cimg): circles = [] try: circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=0,maxRadius=0) except: circles = cv2.HoughCircles(img, cv.CV_HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0) if(circles is None): return circles = np.uint16(np.around(circles)) for i in circles[0, :]: # draw the outer circle cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) # draw the center of the circle cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
Example #8
Source File: MeterReader.py From Pointer-meter-identification-and-reading with MIT License | 5 votes |
def detect_circles(self,gray,img): circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 100, param2=150, minRadius=160) circles = np.uint16(np.around(circles)) # 把circles包含的圆心和半径的值变成整数 cir = img.copy() for i in circles[0, :]: cv2.circle(cir, (i[0], i[1]), i[2], (0, 255, 0), 2, cv2.LINE_AA) # 画圆 cv2.circle(cir, (i[0], i[1]), 2, (0, 255, 0), 2, cv2.LINE_AA) # 画圆心 cv2.imshow("circles", cir) return cir # 霍夫直线变换:检测指针
Example #9
Source File: parse_primitives.py From geosolver with Apache License 2.0 | 5 votes |
def _get_circles(image_segment, params): temp = cv2.HoughCircles(image_segment.segmented_image, cv2.HOUGH_GRADIENT, params.dp, params.minDist, param1=params.param1, param2=params.param2, minRadius=params.minRadius, maxRadius=params.maxRadius) if temp is None: return [] circle_tuples = temp[0] if len(circle_tuples) > params.max_num: circle_tuples = circle_tuples[:params.max_num] circles = [instantiators['circle'](instantiators['point'](x, y), radius) for x, y, radius in circle_tuples] return circles
Example #10
Source File: trainer_matches.py From Yugioh-bot with MIT License | 5 votes |
def capture_white_circles(self, x_limit=480, y_limit=670): self.prep_for_white_circles() img = cv2.cvtColor(self.white_query, cv2.COLOR_BGR2GRAY) cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 40, param1=50, param2=30, minRadius=5, maxRadius=60) if circles is None: return circles = np.uint16(np.around(circles)) for i in circles[0, :]: if i[0] <= x_limit and i[1] <= y_limit: self.circlePoints.append((i[0], i[1])) if self._debug: self.draw_circles(circles, cimg)
Example #11
Source File: rpotter.py From rpotter with MIT License | 5 votes |
def FindNewPoints(): global old_frame,old_gray,p0,mask,color,ig,img,frame try: try: old_frame = cam.capture(stream, format='jpeg') except: print("resetting points") data = np.fromstring(stream.getvalue(), dtype=np.uint8) old_frame = cv2.imdecode(data, 1) cv2.flip(old_frame,1,old_frame) old_gray = cv2.cvtColor(old_frame,cv2.COLOR_BGR2GRAY) #cv2.equalizeHist(old_gray,old_gray) #old_gray = cv2.GaussianBlur(old_gray,(9,9),1.5) #dilate_kernel = np.ones(dilation_params, np.uint8) #old_gray = cv2.dilate(old_gray, dilate_kernel, iterations=1) #TODO: trained image recognition p0 = cv2.HoughCircles(old_gray,cv2.HOUGH_GRADIENT,3,100,param1=100,param2=30,minRadius=4,maxRadius=15) p0.shape = (p0.shape[1], 1, p0.shape[2]) p0 = p0[:,:,0:2] mask = np.zeros_like(old_frame) ig = [[0] for x in range(20)] print("finding...") TrackWand() #This resets the scene every three seconds threading.Timer(3, FindNewPoints).start() except: e = sys.exc_info()[1] print("FindWand Error: %s" % e ) End() exit
Example #12
Source File: segscanner.py From Map-A-Droid with GNU General Public License v3.0 | 5 votes |
def cropImage(self, image, raidNo, radius): gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) gray=cv2.GaussianBlur(gray, (7, 7), 2) output = image.copy() height, width, channel = output.shape output = output[0:height*2/3,0:width] image_cols, image_rows, _ = image.shape circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50,param2=30, minRadius=radius, maxRadius=radius) if circles is not None: circles = np.round(circles[0, :]).astype("int") for (x, y, r) in circles: log.debug('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) +') ] ' + 'cropImage: Detect crop coordinates x: ' + str(x) +' y: ' + str(y) +' with radius: ' + str(r)) new_crop = output[y-r:y+r, x-r:x+r] return new_crop return False
Example #13
Source File: fileObserver.py From Map-A-Droid with GNU General Public License v3.0 | 5 votes |
def cropImage(self, screenshot, captureTime, captureLat, captureLng, src_path): p = None raidNo = 0 processes = [] hash = str(time.time()) orgScreen = screenshot height, width, channel = screenshot.shape gray=cv2.cvtColor(screenshot,cv2.COLOR_BGR2GRAY) gray=cv2.GaussianBlur(gray, (7, 7), 2) minRadius = int(((width / 4.736)) / 2) maxRadius = int(((width / 4.736)) / 2) log.debug('Searching for Raid Circles with Radius from %s to %s px' % (str(minRadius), str(maxRadius))) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50,param2=30, minRadius=minRadius, maxRadius=maxRadius) if circles is not None: circles = np.round(circles[0, :]).astype("int") for (x, y, r) in circles: log.debug('Found Circle with x:%s, y:%s, r:%s' % (str(x), str(y), str(r))) raidNo += 1 raidCropFilepath = os.path.join(args.temp_path, str(hash) + "_raidcrop" + str(raidNo) +".jpg") new_crop = orgScreen[y-r-int((r*2*0.03)):y+r+int((r*2*0.75)), x-r-int((r*2*0.03)):x+r+int((r*2*0.3))] cv2.imwrite(raidCropFilepath, new_crop) if args.ocr_multitask: p = multiprocessing.Process(target=RaidScan.process, name='OCR-crop-analysis-' + str(raidNo), args=(raidCropFilepath, hash, raidNo, captureTime, captureLat, captureLng, src_path, r)) else: p = Thread(target=RaidScan.process, name='OCR-processing', args=(raidCropFilepath, hash, raidNo, captureTime, captureLat, captureLng, src_path, r)) processes.append(p) p.daemon = True p.start()
Example #14
Source File: FOVMultiWellsSplitter.py From tierpsy-tracker with MIT License | 5 votes |
def find_circular_wells(self): """Simply use Hough transform to find circles in MultiWell Plate rgb image. The parameters used are optimised for 24 or 48WP""" dwnscl_factor = self.img_shape[0]/self.blur_im.shape[0] # find circles # parameters in downscaled units circle_goodness = 70; highest_canny_thresh = 10; min_well_dist = self.blur_im.shape[1]/3; # max 3 wells along short side. bank on FOV not taking in all the entirety of the well min_well_radius = self.blur_im.shape[1]//7; # if 48WP 3 wells on short side ==> radius <= side/6 max_well_radius = self.blur_im.shape[1]//4; # if 24WP 2 wells on short side. COnsidering intrawells space, radius <= side/4 # find circles _circles = cv2.HoughCircles(self.blur_im, cv2.HOUGH_GRADIENT, dp=1, minDist=min_well_dist, param1=highest_canny_thresh, param2=circle_goodness, minRadius=min_well_radius, maxRadius=max_well_radius) _circles = np.squeeze(_circles); # because why the hell is there an empty dimension at the beginning? # convert back to pixels _circles *= dwnscl_factor; # output back into class property self.wells['x'] = _circles[:,0].astype(int) self.wells['y'] = _circles[:,1].astype(int) self.wells['r'] = _circles[:,2].astype(int) return
Example #15
Source File: blob.py From pypot with GNU General Public License v3.0 | 5 votes |
def detect_blob(self, img, filters): """ "filters" must be something similar to: filters = { 'R': (150, 255), # (min, max) 'S': (150, 255), } """ acc_mask = ones(img.shape[:2], dtype=uint8) * 255 rgb = img.copy() hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) for c, (min, max) in filters.items(): img = rgb if c in 'RGB' else hsv mask = img[:, :, self.channels[c]] mask[mask < min] = 0 mask[mask > max] = 0 acc_mask &= mask kernel = ones((5, 5), uint8) acc_mask = cv2.dilate(cv2.erode(acc_mask, kernel), kernel) circles = cv2.HoughCircles(acc_mask, cv2.HOUGH_GRADIENT, 3, img.shape[0] / 5.) return circles.reshape(-1, 3) if circles is not None else []
Example #16
Source File: pogoWindows.py From Map-A-Droid with GNU General Public License v3.0 | 4 votes |
def __readCircleCords(self,filename,hash,ratio, crop = False, canny=False): log.debug("__readCircleCords: Reading circlescords") try: screenshotRead = cv2.imread(filename) except: log.error("Screenshot corrupted :(") return False if screenshotRead is None: log.error("Screenshot corrupted :(") return False height, width, _ = screenshotRead.shape if crop: screenshotRead = screenshotRead[int(height)-int(height/5):int(height),int(width)/2-int(width)/8:int(width)/2+int(width)/8] log.debug("__readCircleCords: Determined screenshot scale: " + str(height) + " x " + str(width)) gray = cv2.cvtColor(screenshotRead, cv2.COLOR_BGR2GRAY) # detect circles in the image radMin = int((width / float(ratio) - 3) / 2) radMax = int((width / float(ratio) + 3) / 2) if canny: gray = cv2.GaussianBlur(gray, (3, 3), 0) gray = cv2.Canny(gray, 100, 50, apertureSize=3) log.debug("__readCircleCords: Detect radius of circle: Min " + str(radMin) + " Max " + str(radMax)) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, width / 8, param1=100, param2=15, minRadius=radMin, maxRadius=radMax) circle = 0 # ensure at least some circles were found if circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: log.debug("__readCircleCords: Found Circle x: %s y: %s" % (str(width/2), str((int(height)-int(height/5))+y))) return True, width/2, (int(height)-int(height/5))+y, height, width else: log.debug("__readCircleCords: Found no Circle") return False, 0, 0, 0, 0
Example #17
Source File: pogoWindows.py From Map-A-Droid with GNU General Public License v3.0 | 4 votes |
def __readCircleCount(self,filename,hash,ratio, xcord = False, crop = False, click = False, canny=False): log.debug("__readCircleCount: Reading circles") try: screenshotRead = cv2.imread(filename) except: log.error("Screenshot corrupted :(") return -1 if screenshotRead is None: log.error("Screenshot corrupted :(") return -1 height, width, _ = screenshotRead.shape if crop: screenshotRead = screenshotRead[int(height)-int(height/4.5):int(height),int(width)/2-int(width)/8:int(width)/2+int(width)/8] log.debug("__readCircleCount: Determined screenshot scale: " + str(height) + " x " + str(width)) gray = cv2.cvtColor(screenshotRead, cv2.COLOR_BGR2GRAY) # detect circles in the image radMin = int((width / float(ratio) - 3) / 2) radMax = int((width / float(ratio) + 3) / 2) if canny: gray = cv2.GaussianBlur(gray, (3, 3), 0) gray = cv2.Canny(gray, 100, 50, apertureSize=3) log.debug("__readCircleCount: Detect radius of circle: Min " + str(radMin) + " Max " + str(radMax)) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, width / 8, param1=100, param2=15, minRadius=radMin, maxRadius=radMax) circle = 0 # ensure at least some circles were found if circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: if not xcord: circle += 1 if click: log.debug('__readCircleCount: found Circle - click it') self.screenWrapper.click(width/2, ((int(height)-int(height/4.5)))+y) time.sleep(2) else: if x >= (width / 2) - 100 and x <= (width / 2) + 100 and y >= (height - (height / 3)): circle += 1 if click: log.debug('__readCircleCount: found Circle - click on: it' ) self.screenWrapper.click(width/2, ((int(height)-int(height/4.5)))+y) time.sleep(2) log.debug("__readCircleCount: Determined screenshot to have " + str(circle) + " Circle.") return circle else: log.debug("__readCircleCount: Determined screenshot to have 0 Circle") return -1
Example #18
Source File: detect_new.py From RaspberryCar with MIT License | 4 votes |
def TennisDetect(self, img, VideoReturn): # 检测网球(利用霍夫圆检测和HSV色彩检测) x_pos = 0 # initialize the tennis's position y_pos = 0 radius = 0 img_out = copy.copy(img) img = img[self.cut_edge:479, :, :] img = cv2.blur(img, (5,5)) # denoising hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # rgb to HSV # img_out = copy.copy(hsv_img[:, :, 0]) # img_out = cv2.cvtColor(img_out, cv2.COLOR_GRAY2BGR) gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # rgb to gray circles = cv2.HoughCircles(gray_img, cv2.HOUGH_GRADIENT, 1, 60, param1=100, param2=20, minRadius=15, maxRadius=60) # HOUGH circle detection if circles is not None: x = circles[0][:, 0].astype(int) # extract the x, y, r of all detected circles y = circles[0][:, 1].astype(int) r = circles[0][:, 2].astype(int) s_r = (r/1.5).astype(int) num = circles[0].shape[0] rate = np.zeros(num) for i in range(num): # traverse all detected circles detect_area = (hsv_img[y[i]-s_r[i]: y[i]+s_r[i], x[i]-s_r[i]:x[i]+s_r[i]]) # A square in the detected circle height, width, channel = detect_area.shape if height !=0 and width !=0: tennis_color_mask = cv2.inRange(detect_area, self.lower_range, self.higher_range) num_point = np.sum(tennis_color_mask / 255) rate[i] = num_point / (height * width) img_out = cv2.circle(img_out, (x[i], y[i]+self.cut_edge), r[i], (0,255,0), thickness=2) i = np.argmax(rate) # select the circle with the maximum rate as the detected tennis if rate[i] > 0.4: # if the percent of tennis_color_point in detect_area > 50%, then regard it as the tennis x_pos = x[i] y_pos = y[i] radius = r[i] print('x: ', x[i], ' y: ', y[i], ' r: ', r[i], ' rate: ', rate[i]) if VideoReturn: # if it needs to return the frame with the detected tennis img_out = cv2.circle(img_out, (x_pos, y_pos+self.cut_edge), radius, (0,0,255), thickness=10) return img_out, x_pos, y_pos, radius else: # if it only needs to return the position of the detected tennis return x_pos, y_pos, radius
Example #19
Source File: detect.py From RaspberryCar with MIT License | 4 votes |
def TennisDetect(self, img, VideoReturn): # 检测网球(利用霍夫圆检测和HSV色彩检测) x_pos = 0 # initialize the tennis's position y_pos = 0 radius = 0 img = cv2.blur(img, (5,5)) # denoising hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # rgb to HSV (h_img, s_img, v_img) = cv2.split(hsv_img) gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # rgb to gray # gray_img = cv2.equalizeHist(gray_img) # hist equalization circles = cv2.HoughCircles(gray_img, cv2.HOUGH_GRADIENT, 1, 120, param1=100, param2=20, minRadius=15, maxRadius=60) # HOUGH circle detection if circles is not None: x = circles[0][:, 0].astype(int) # extract the x, y, r of all detected circles y = circles[0][:, 1].astype(int) r = circles[0][:, 2].astype(int) s_r = (r/1.5).astype(int) num = circles[0].shape[0] distance = np.ones(num) * 100 mean_h = np.zeros(num) mean_s = np.zeros(num) for i in range(num): # traverse all detected circles: detect_area_h = (h_img[y[i]-s_r[i]: y[i]+s_r[i], x[i]-s_r[i]:x[i]+s_r[i]]) # A square in the detected circle (H) detect_area_s = (s_img[y[i]-s_r[i]: y[i]+s_r[i], x[i]-s_r[i]:x[i]+s_r[i]]) # A square in the detected circle (S) # Through 33 photos of the tennis captured by Raspberry Camera, we find the average H of tennis areas is 36, the average S of tennis areas is 163, and the var of H is much smaller than that of S. if len(detect_area_h): num_point = detect_area_h[detect_area_h > 30 and detect_area_h < 40] # height, width = detect_area_h.shape # rate = num_point / (height*width) # print('rate', rate) mean_h[i] = np.mean(detect_area_h) mean_s[i] = np.mean(detect_area_s) distance[i] = np.sqrt(0.98*(mean_h[i] - 35)**2 + 0.02*(mean_s[i] - 163)**2) i = np.argmin(distance) # select the circle with the minimum distance as the detected tennis if distance[i] < 20: # if distance > 15, the selected circle cannot be a tennis x_pos = x[i] y_pos = y[i] radius = r[i] print('x: ', x[i], ' y: ', y[i], ' r: ', r[i], ' distance: ', distance[i], ' mean_h:', mean_h[i], ' mean_s:', mean_s[i]) if VideoReturn: # if it needs to return the frame with the detected tennis img_out = copy.copy(img) img_out = cv2.circle(img_out, (x_pos, y_pos), radius, (0,0,255), thickness=10) return img_out, x_pos, y_pos, radius else: # if it only needs to return the position of the detected tennis return x_pos, y_pos, radius
Example #20
Source File: EyeTrackingLib.py From ImageProcessingProjects with MIT License | 4 votes |
def find_eye_center(image): """ Find center of eye using Fabian's algorithm :param image: Gray scale image of eye :return: row, col identified as center """ # print image.shape global showImage scaled_image = utils.image_resize(image.copy(), width=EYE_ROI_WIDTH) gradient_energy_x = cv2.Sobel(scaled_image, cv2.CV_64F, 1, 0, ksize=3) gradient_energy_y = cv2.Sobel(scaled_image, cv2.CV_64F, 0, 1, ksize=3) gradient_magnitude = (gradient_energy_x ** 2 + gradient_energy_y ** 2) ** 0.5 threshold = np.mean(gradient_magnitude) + np.std(gradient_magnitude) * 3 gradient_energy_x /= gradient_magnitude gradient_energy_y /= gradient_magnitude mask = gradient_magnitude < threshold gradient_energy_x[mask] = 0 gradient_energy_y[mask] = 0 scaled_image = cv2.GaussianBlur(scaled_image, (5, 5), 0, 0) inverted_image = 255 * np.ones_like(scaled_image) - scaled_image if showImage: # cv2.HoughCircles(scaled_image, cv2.HOUGH_GRADIENT, 2, 12.0) cv2.imshow("EyeDebug", inverted_image) if (cv2.waitKey() & 0xFF) == ord('s'): showImage = False cv2.destroyWindow('EyeDebug') indices = np.indices(inverted_image.shape).astype(np.float32) indices += 1e-8 output_sum = np.zeros_like(inverted_image).astype(np.float32) for row in range(output_sum.shape[0]): for col in range(output_sum.shape[1]): val1 = (indices[0] - row) * gradient_energy_y val2 = (indices[1] - col) * gradient_energy_x val = (val1 + val2) output_sum += inverted_image * (val - val.mean()) / val.std() # compute_location_weight(row, col, inverted_image, gradient_energy_x, gradient_energy_y) index = np.unravel_index(np.argmax(output_sum), output_sum.shape) rescaled_index = ( index[0] * image.shape[0] / scaled_image.shape[0], index[1] * image.shape[1] / scaled_image.shape[1]) return rescaled_index
Example #21
Source File: lambda_function.py From aws-builders-fair-projects with Apache License 2.0 | 4 votes |
def detect_sushi(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.medianBlur(gray, 5) circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, dp=1, minDist=100, param1=50, param2=30, minRadius=170, maxRadius=400) if circles is None: return None obj_width = 0 obj_height = 0 circles = np.uint16(np.around(circles)) for (x, y, r) in circles[0]: x, y, r = int(x), int(y), int(r) obj_top = int(y - r - 10) if obj_top < 0: obj_top = 0 obj_left = int(x - r - 10) if obj_left < 0: obj_left = 0 obj_width = int(r*2+20) obj_right = obj_left + obj_width if obj_right > WIDTH: obj_right = WIDTH obj_width = WIDTH - obj_left obj_height = int(r*2+20) obj_bottom = obj_top + obj_height if obj_bottom > HEIGHT: obj_bottom = HEIGHT obj_height = HEIGHT - obj_top break if obj_width < 380 or obj_height < 380 or obj_width > 420 or obj_height > 420: # skip if circle is small or too large return None # return the detected rectangle return (obj_top, obj_bottom, obj_left, obj_right) # infinite loop to detect sushi
Example #22
Source File: ball_tracker.py From SunFounder_PiCar-V with GNU General Public License v2.0 | 4 votes |
def find_blob() : radius = 0 # Load input image _, bgr_image = img.read() orig_image = bgr_image bgr_image = cv2.medianBlur(bgr_image, 3) # Convert input image to HSV hsv_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2HSV) # Threshold the HSV image, keep only the red pixels lower_red_hue_range = cv2.inRange(hsv_image, (0, 100, 100), (10, 255, 255)) upper_red_hue_range = cv2.inRange(hsv_image, (160, 100, 100), (179, 255, 255)) # Combine the above two images red_hue_image = cv2.addWeighted(lower_red_hue_range, 1.0, upper_red_hue_range, 1.0, 0.0) red_hue_image = cv2.GaussianBlur(red_hue_image, (9, 9), 2, 2) # Use the Hough transform to detect circles in the combined threshold image circles = cv2.HoughCircles(red_hue_image, cv2.HOUGH_GRADIENT, 1, 120, 100, 20, 10, 0) circles = np.uint16(np.around(circles)) # Loop over all detected circles and outline them on the original image all_r = np.array([]) # print("circles: %s"%circles) if circles is not None: try: for i in circles[0,:]: # print("i: %s"%i) all_r = np.append(all_r, int(round(i[2]))) closest_ball = all_r.argmax() center=(int(round(circles[0][closest_ball][0])), int(round(circles[0][closest_ball][1]))) radius=int(round(circles[0][closest_ball][2])) if draw_circle_enable: cv2.circle(orig_image, center, radius, (0, 255, 0), 5) except IndexError: pass # print("circles: %s"%circles) # Show images if show_image_enable: cv2.namedWindow("Threshold lower image", cv2.WINDOW_AUTOSIZE) cv2.imshow("Threshold lower image", lower_red_hue_range) cv2.namedWindow("Threshold upper image", cv2.WINDOW_AUTOSIZE) cv2.imshow("Threshold upper image", upper_red_hue_range) cv2.namedWindow("Combined threshold images", cv2.WINDOW_AUTOSIZE) cv2.imshow("Combined threshold images", red_hue_image) cv2.namedWindow("Detected red circles on the input image", cv2.WINDOW_AUTOSIZE) cv2.imshow("Detected red circles on the input image", orig_image) k = cv2.waitKey(5) & 0xFF if k == 27: return (0, 0), 0 if radius > 3: return center, radius else: return (0, 0), 0
Example #23
Source File: eye.py From faceai with MIT License | 4 votes |
def houghCircles(path, counter): img = cv2.imread(path, 0) # img = cv2.medianBlur(img, 5) x = cv2.Sobel(img, -1, 1, 0, ksize=3) y = cv2.Sobel(img, -1, 0, 1, ksize=3) absx = cv2.convertScaleAbs(x) absy = cv2.convertScaleAbs(y) img = cv2.addWeighted(absx, 0.5, absy, 0.5, 0) # ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) # channels = cv2.split(ycrcb) # cv2.equalizeHist(channels[0], channels[0]) #输入通道、输出通道矩阵 # cv2.merge(channels, ycrcb) #合并结果通道 # cv2.cvtColor(ycrcb, cv2.COLOR_YCR_CB2BGR, img) # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # cv2.imshow("img2", img) # cv2.imshow("grayimg", grayimg) circles = cv2.HoughCircles( img, cv2.HOUGH_GRADIENT, 1, 50, param1=50, param2=10, minRadius=2, maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0, :]: # draw the outer circle # cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 1) # draw the center of the circle cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 2) # cv2.imshow("img" + str(counter), cimg) return (i[0] + 3, i[1] + 3) #彩色直方图均衡化