本文整理匯總了Python中cv2.minEnclosingCircle方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.minEnclosingCircle方法的具體用法?Python cv2.minEnclosingCircle怎麽用?Python cv2.minEnclosingCircle使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.minEnclosingCircle方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_contour_centers
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def get_contour_centers(contours: np.ndarray) -> np.ndarray:
"""
Calculate the centers of the contours
:param contours: Contours detected with find_contours
:return: object centers as numpy array
"""
if len(contours) == 0:
return np.array([])
# ((x, y), radius) = cv2.minEnclosingCircle(c)
centers = np.zeros((len(contours), 2), dtype=np.int16)
for i, c in enumerate(contours):
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
centers[i] = center
return centers
示例2: colorTarget
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def colorTarget(color_range=((0, 0, 0), (255, 255, 255))):
image = cam.newImage()
if filter == 'RGB':
frame_to_thresh = image.copy()
else:
frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert image to hsv colorspace RENAME THIS TO IMAGE_HSV
thresh = cv2.inRange(frame_to_thresh, color_range[0], color_range[1])
mask = thresh
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] # generates number of contiguous "1" pixels
if len(cnts) == 0: # begin processing if there are "1" pixels discovered
return np.array([None, None, 0])
else:
c = max(cnts, key=cv2.contourArea) # return the largest target area
((x, y), radius) = cv2.minEnclosingCircle(c)
if radius > 4:
return np.array([round(x, 1), round(y, 1), round(radius, 1)])
示例3: find_red
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def find_red(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv,(130,130,180),(255,255,255))
mask = cv2.erode(mask, np.ones((2,1)) , iterations=1)
mask = cv2.dilate(mask, None, iterations=3)
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
frame=img.copy()
###based on example from http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv
if len(cnts) > 0:
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
if radius > 3:
cv2.circle(frame, (int(x), int(y)), 12,(0, 255, 255), 2)
return frame
示例4: colorTarget
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def colorTarget(color_range=((0, 0, 0), (255, 255, 255))):
image = cam.newImage()
if filter == 'RGB':
frame_to_thresh = image.copy()
else:
frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert image to hsv colorspace RENAME THIS TO IMAGE_HSV
thresh = cv2.inRange(frame_to_thresh, color_range[0], color_range[1])
# apply a blur function
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) # Apply blur
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # Apply blur 2nd iteration
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] # generates number of contiguous "1" pixels
if len(cnts) > 0: # begin processing if there are "1" pixels discovered
c = max(cnts, key=cv2.contourArea) # return the largest target area
((x, y), radius) = cv2.minEnclosingCircle(c)
return np.array([round(x, 1), round(y, 1), round(radius, 1)])
else:
return np.array([None, None, 0])
示例5: returnMaxAreaCircle
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def returnMaxAreaCircle(self, mask):
"""it returns the circle sorrounding the contour with the largest area.
@param mask the binary image to use in the function
@return get the center (x, y) and the radius of the circle
"""
if(mask is None): return (None, None, None)
mask = np.copy(mask)
if(len(mask.shape) == 3):
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(mask, 1, 2)
area_array = np.zeros(len(contours)) #contains the area of the contours
counter = 0
for cnt in contours:
area_array[counter] = cv2.contourArea(cnt)
counter += 1
if(area_array.size==0): return (None, None, None) #the array is empty
max_area_index = np.argmax(area_array) #return the index of the max_area element
cnt = contours[max_area_index]
(x,y),radius = cv2.minEnclosingCircle(cnt)
return (int(x),int(y), int(radius))
示例6: get_output_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def get_output_image(path):
img = cv2.imread(path,2)
img_org = cv2.imread(path)
ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for j,cnt in enumerate(contours):
epsilon = 0.01*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
hull = cv2.convexHull(cnt)
k = cv2.isContourConvex(cnt)
x,y,w,h = cv2.boundingRect(cnt)
if(hierarchy[0][j][3]!=-1 and w>10 and h>10):
#putting boundary on each digit
cv2.rectangle(img_org,(x,y),(x+w,y+h),(0,255,0),2)
#cropping each image and process
roi = img[y:y+h, x:x+w]
roi = cv2.bitwise_not(roi)
roi = image_refiner(roi)
th,fnl = cv2.threshold(roi,127,255,cv2.THRESH_BINARY)
# getting prediction of cropped image
pred = predict_digit(roi)
print(pred)
# placing label on each digit
(x,y),radius = cv2.minEnclosingCircle(cnt)
img_org = put_label(img_org,pred,x,y)
return img_org
示例7: _find_contours
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def _find_contours(image):
"""
Helper function for finding contours of image.
Returns coordinates of contours.
"""
# Increase constrast in image to increase changes of finding
# contours.
processed = _increase_contrast(image)
# Get the gray-scale of the image.
gray = cv2.cvtColor(processed, cv2.COLOR_BGR2GRAY)
# Detect contour(s) in the image.
cnts = cv2.findContours(
gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
center = None
# At least ensure that some contours were found.
if len(cnts) > 0:
# Find the largest contour in the mask.
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
# Assume the radius is of a certain size.
if radius > 100:
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
return (center, radius)
示例8: detect_container
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def detect_container(img):
""" detects the inner boundary of the petridish in an image
input
img: grayscale image as numpy array
ouput:
cnt: an opencv contour object representing the inner border
of the petridish
"""
# edge detection
edges = cv.Canny(img,18,32)
# dilate edges
# to close small openings
kernel = np.ones((2,2),np.uint8)
edges = cv.dilate(edges,kernel,iterations = 2)
#find contours
im2, contours, hierarchy = cv.findContours(edges, cv.RETR_TREE,
cv.CHAIN_APPROX_NONE)
#detect the biggest contour
outer_cntIndex = np.argmax([cv.contourArea(cnt) for cnt in contours])
outer_cnt = contours[outer_cntIndex]
#filter contours that have area > 0.6*Area of max contour
filt_cnts = [cnt for cnt in contours if cv.contourArea(cnt)>0.6*cv.contourArea(outer_cnt)]
#get the minimun contour of the filterd ones
inner_cntIndex = np.argmin([cv.contourArea(cnt) for cnt in filt_cnts])
inner_cnt= filt_cnts[inner_cntIndex]
# get the minimin enclosing circle for the inner contour
# to get a perfect circular shape
# (x,y),radius = cv.minEnclosingCircle(inner_cnt)
# center = (int(x),int(y))
# radius = int(radius)
# cv.circle(img,center,radius,(255,0,255),1)
return inner_cnt
示例9: test_inner_contour
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def test_inner_contour():
""" displays the inner contour and the minimum circled enclosed on it
"""
#testing inner contour
isExit = False
for frame in frames_list:
#open the frame in grayscake
img = cv.imread(path + frame, 0)
#call detect_container from tools_single.py
inner_cnt = tools.detect_container(img)
#conver the frame to BGR
img = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
#get minimin enclosing circle and draw it
#along with inner contour
(x,y),radius = cv.minEnclosingCircle(inner_cnt)
center = (int(x),int(y))
radius = int(radius)
cv.circle(img,center,radius,(0,255,0),1)
cv.drawContours(img, [inner_cnt], -1, (200,0,0), 1)
#display frame
cv.imshow('image',img)
# delay and 'q' key press to exit the animation
if cv.waitKey(50) & 0xFF == ord('q'):
isExit = True
break
while(not isExit):
# prevent exit the display window till the user presses 'q'
if cv.waitKey(1) & 0xFF == ord('q'):
break
cv.destroyAllWindows()
return None
示例10: find_markers_from_img_thresh
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def find_markers_from_img_thresh(img_thresh, max_dist_between_centers=3, min_radius_circle=4,
max_radius_circle=35, min_radius_marker=7):
contours = cv2.findContours(img_thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
list_potential_markers = []
for cnt in contours:
(x, y), radius = cv2.minEnclosingCircle(cnt)
if not min_radius_circle < radius < max_radius_circle:
continue
center = (int(round(x)), int(round(y)))
radius = int(radius)
list_potential_markers.append(PotentialMarker(center, radius, cnt))
list_potential_markers = sorted(list_potential_markers, key=lambda m: m.x)
list_good_candidates = []
for i, potential_marker in enumerate(list_potential_markers):
if potential_marker.is_merged:
continue
marker1 = Marker(potential_marker)
center_marker = marker1.get_center()
for potential_marker2 in list_potential_markers[i + 1:]:
if potential_marker.is_merged:
continue
center_potential = potential_marker2.get_center()
if center_potential[0] - center_marker[0] > max_dist_between_centers:
break
dist = euclidean_dist_2_pts(center_marker, center_potential)
if dist <= max_dist_between_centers:
marker1.add_circle(potential_marker2)
center_marker = marker1.get_center()
if marker1.nb_circles() > 2 and marker1.radius >= min_radius_marker:
list_good_candidates.append(marker1)
marker1.get_id_from_slice(img_thresh)
return list_good_candidates
示例11: detectRoundel
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def detectRoundel( frame, debug=False ):
global g_mser
global THRESHOLD_FRACTION
if g_mser == None:
g_mser = cv2.MSER( _delta = 10, _min_area=100, _max_area=300*50*2 )
gray = cv2.cvtColor( frame, cv2.COLOR_BGR2GRAY )
contours = g_mser.detect(gray, None)
rectangles = []
circles = []
for cnt in contours:
rect = cv2.minAreaRect(cnt)
area = len(cnt) # MSER returns all points within area, not boundary points
rectangleArea = float(rect[1][0]*rect[1][1])
rectangleAspect = max(rect[1][0], rect[1][1]) / float(min(rect[1][0], rect[1][1]))
if area/rectangleArea > 0.70 and rectangleAspect > 3.0:
(x,y),(w,h),angle = rect
rectangles.append( ((int(x+0.5),int(y+0.5)), (int(w+0.5),int(h+0.5)), int(angle)) )
cir = cv2.minEnclosingCircle(cnt)
(x,y),radius = cir
circleArea = math.pi*radius*radius
if area/circleArea > 0.64:
circles.append( ((int(x+0.5),int(y+0.5)),int(radius+0.5)) )
rectangles = removeDuplicities( rectangles )
result = matchCircRect( circles=circles, rectangles=rectangles )
if debug:
for rect in rectangles:
box = cv2.cv.BoxPoints(rect)
box = np.int0(box)
cv2.drawContours( frame,[box],0,(255,0,0),2)
for cir in circles:
(x,y),radius = cir
center = (int(x),int(y))
radius = int(radius)
cv2.circle(frame, center, radius, (0,255,0), 2)
if result:
(x1,y1),(x2,y2) = result
cv2.line(frame, (int(x1),int(y1)), (int(x2),int(y2)), (0,0,255), 3)
return result
示例12: getColor
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def getColor(frame):
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
maxsum = 0
color = None
color_dict = colorList.getColorList()
# 對每個顏色進行判斷
for d in color_dict:
# 根據閾值構建掩膜
mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1])
# 腐蝕操作
mask = cv2.erode(mask, None, iterations=2)
# 膨脹操作,其實先腐蝕再膨脹的效果是開運算,去除噪點
mask = cv2.dilate(mask, None, iterations=2)
img, cnts, hiera = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 有輪廓才進行後麵的判斷
if len(cnts) > 0:
# 計算識別區域的麵積
sum = 0
for c in cnts:
sum += cv2.contourArea(c)
# 找到最大麵積並找到質心
if sum > maxsum :
maxsum = sum
if maxsum != 0:
color = d
else:
color = None
# 找到麵積最大的輪廓
c = max(cnts, key = cv2.contourArea)
# 確定麵積最大的輪廓的外接圓
((x, y), radius) = cv2.minEnclosingCircle(c)
# 計算輪廓的矩
M = cv2.moments(c)
# 計算質心
center = (int(M["m10"]/M["m00"]), int(M["m01"]/M["m00"]))
return color, center
示例13: findColor
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def findColor(self, frame_image):
hsv = cv2.cvtColor(frame_image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, colorLower, colorUpper)#1
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
center = None
if len(cnts) > 0:
self.findColorDetection = 1
c = max(cnts, key=cv2.contourArea)
((self.box_x, self.box_y), self.radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
X = int(self.box_x)
Y = int(self.box_y)
error_Y = 240 - Y
error_X = 320 - X
# CVThread.servoMove(CVThread.P_servo, CVThread.P_direction, error_X)
CVThread.servoMove(CVThread.T_servo, CVThread.T_direction, error_Y)
# if CVThread.X_lock == 1 and CVThread.Y_lock == 1:
if CVThread.Y_lock == 1:
led.setColor(255,78,0)
# switch.switch(1,1)
# switch.switch(2,1)
# switch.switch(3,1)
else:
led.setColor(0,78,255)
# switch.switch(1,0)
# switch.switch(2,0)
# switch.switch(3,0)
else:
self.findColorDetection = 0
move.motorStop()
self.pause()
示例14: process
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def process(self, image):
self.detected = False
hsv_frame = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_frame, self.__hsv_bounds[0], self.__hsv_bounds[1])
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
if len(contours) == 0:
return
largest_contour = max(contours, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(largest_contour)
M = cv2.moments(largest_contour)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
self.circle_coordonates = (center, int(radius))
self.detected = True
示例15: boundingCircle
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import minEnclosingCircle [as 別名]
def boundingCircle(self):
"""
**SUMMARY**
This function calculates the minimum bounding circle of the blob in the image
as an (x,y,r) tuple
**RETURNS**
An (x,y,r) tuple where (x,y) is the center of the circle and r is the radius
**EXAMPLE**
>>> img = Image("RatMask.png")
>>> blobs = img.findBlobs()
>>> print blobs[-1].boundingCircle()
"""
try:
import cv2
except:
logger.warning("Unable to import cv2")
return None
# contour of the blob in image
contour = self.contour()
points = []
# list of contour points converted to suitable format to pass into cv2.minEnclosingCircle()
for pair in contour:
points.append([[pair[0], pair[1]]])
points = np.array(points)
(cen, rad) = cv2.minEnclosingCircle(points);
return (cen[0], cen[1], rad)
#---------------------------------------------