def getweight(self, mask_mat=None):
#gray_mask = cv2.cvtColor(mask_mat, cv2.COLOR_BGR2GRAY)
gray_mask=mask_mat
ret, bin_mask = cv2.threshold(gray_mask,1,1,0)
_, contours, _ = cv2.findContours(bin_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
weights = np.zeros_like(bin_mask, dtype=np.float)
weights = cv2.drawContours(weights, contours, -1, (1), 5)
weights = cv2.GaussianBlur(weights, (41,41), 1000)
weights = np.multiply(weights,10)+0.6
return weights
python类RETR_EXTERNAL的实例源码
def identify_OD(image):
newfin = cv2.dilate(image, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations=2)
mask = np.ones(newfin.shape[:2], dtype="uint8") * 255
y1, ycontours, yhierarchy = cv2.findContours(newfin.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
prev_contour = ycontours[0]
for cnt in ycontours:
if cv2.contourArea(cnt) >= cv2.contourArea(prev_contour):
prev_contour = cnt
cv2.drawContours(mask, [cnt], -1, 0, -1)
M = cv2.moments(prev_contour)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
#print(cx,cy)
return (cx,cy)
def identify_OD(image):
newfin = cv2.dilate(image, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations=2)
mask = np.ones(newfin.shape[:2], dtype="uint8") * 255
y1, ycontours, yhierarchy = cv2.findContours(newfin.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
prev_contour = ycontours[0]
for cnt in ycontours:
if cv2.contourArea(cnt) >= cv2.contourArea(prev_contour):
prev_contour = cnt
cv2.drawContours(mask, [cnt], -1, 0, -1)
M = cv2.moments(prev_contour)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
return (cx,cy)
def __find_contours(input, external_only):
"""Sets the values of pixels in a binary image to their distance to the nearest black pixel.
Args:
input: A numpy.ndarray.
external_only: A boolean. If true only external contours are found.
Return:
A list of numpy.ndarray where each one represents a contour.
"""
if(external_only):
mode = cv2.RETR_EXTERNAL
else:
mode = cv2.RETR_LIST
method = cv2.CHAIN_APPROX_SIMPLE
im2, contours, hierarchy =cv2.findContours(input, mode=mode, method=method)
return contours
def get_contours(name, small, pagemask, masktype):
mask = get_mask(name, small, pagemask, masktype)
_, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
contours_out = []
for contour in contours:
rect = cv2.boundingRect(contour)
xmin, ymin, width, height = rect
if (width < TEXT_MIN_WIDTH or
height < TEXT_MIN_HEIGHT or
width < TEXT_MIN_ASPECT*height):
continue
tight_mask = make_tight_mask(contour, xmin, ymin, width, height)
if tight_mask.sum(axis=0).max() > TEXT_MAX_THICKNESS:
continue
contours_out.append(ContourInfo(contour, rect, tight_mask))
if DEBUG_LEVEL >= 2:
visualize_contours(name, small, contours_out)
return contours_out
def detect_ball(frame):
blurred = cv2.GaussianBlur(frame, (11, 11), 0)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, greenLower, greenUpper)
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
# only proceed if at least one contour was found
if len(cnts) == 0:
return
# find the largest contour in the mask, then use
# it to compute the minimum enclosing circle and
# centroid
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 < 10:
print('Too small')
return
return center, radius
def processContoursinGt(path):
folder = sort_files(path)
length_cont_gt = []
for i in range(20,len(folder)):
newPath = path + "/0 (" + str(i) + ")" + ".png"
img = cv2.imread(newPath,cv2.CV_LOAD_IMAGE_COLOR)
#print "Image in processContour: ",img
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (31, 31), 0)
thresh = cv2.threshold(gray, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
length_cont_gt.append(len(cnts))
return length_cont_gt
def processContoursinFr(path1):
folder1 = sort_files_fr(path1)
length_cont_fr = []
for i in range(1,len(folder1)):
newPath = path1 + "/" + str(i)+ ".jpg"
img = cv2.imread(newPath,cv2.CV_LOAD_IMAGE_COLOR)
#print "Image in processContourinFr: ",img
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (31, 31), 0)
thresh = cv2.threshold(gray, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
length_cont_fr.append(len(cnts))
return length_cont_fr
def FindExternalContour(image_bw):
"""Returns the largest external contour."""
# all external contours
_, contours, _ = cv2.findContours(image_bw.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
logging.debug("found {} external contours in image".format(len(contours)))
# max contour by area size
largest = max(contours, key=lambda cnt: cv2.contourArea(cnt))
return Rect(*cv2.boundingRect(largest))
def ShowSolution(images, puzzle, solution, frame, box):
cell_size = np.array([box.w / 4, box.h / 4])
for piece_type, piece, i, j in solution:
top_left_loc = np.array([box.x, box.y]) + (np.array([j, i]) -
np.array([1, 1])) * cell_size
color = pieces.Colors[piece_type]
piece_img = np.zeros_like(frame)
for square in itertools.product(range(2), range(2)):
if piece[square] == board.SquareType.AIR:
continue
loc = top_left_loc + np.array(square[::-1]) * cell_size
piece_img = cv2.rectangle(piece_img, tuple(loc), tuple(loc + cell_size),
color, -2)
if piece[square] in images:
image = cv2.resize(images[piece[square]], tuple(cell_size))
blend = np.zeros_like(piece_img)
blend[loc[1]:loc[1] + cell_size[1], loc[0]:loc[0] + cell_size[
0]] = image
piece_img = cv2.addWeighted(piece_img, 1.0, blend, 1.0, 0)
piece_gray = cv2.cvtColor(piece_img, cv2.COLOR_RGB2GRAY)
_, piece_gray = cv2.threshold(piece_gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(piece_gray, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
piece_img = cv2.drawContours(piece_img, contours, -1, (255, 255, 255), 3)
frame = cv2.addWeighted(frame, 1.0, piece_img, 0.7, 0)
cv2.imshow("Planes", frame)
def img_contour_extra(im):
# ?????
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(13,7))
bgmask = cv2.morphologyEx(im, cv2.MORPH_CLOSE, kernel)
img_show_hook("??????", bgmask)
# ??????
# ??????????
im2, contours, hierarchy = cv2.findContours(bgmask.copy(), cv2.RETR_EXTERNAL, #????
cv2.CHAIN_APPROX_SIMPLE)
return contours
def img_contour_extra(im):
# ?????
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(13,7))
bgmask = cv2.morphologyEx(im, cv2.MORPH_CLOSE, kernel)
img_show_hook("??????", bgmask)
# ??????
# ??????????
im2, contours, hierarchy = cv2.findContours(bgmask.copy(), cv2.RETR_EXTERNAL, #????
cv2.CHAIN_APPROX_SIMPLE)
return contours
def get_patches(segment_arr):
ret = []
im = segment_arr.astype(np.uint8)
contours = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
hulls = [cv2.convexHull(cont) for cont in contours[1]] #seems my version of CV2 (3.0) uses [1]
for contour_idx in xrange(len(hulls)):
cimg = np.zeros_like(im)
cv2.drawContours(cimg, hulls, contour_idx, color=255, thickness=-1)
pts = np.array(np.where(cimg == 255)).T
ret.append(pts)
return ret
def get_patches(segment_arr):
ret = []
im = segment_arr.astype(np.uint8)*255
contours = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
hulls = [cv2.convexHull(cont) for cont in contours[0]]
for contour_idx in xrange(len(hulls)):
cimg = np.zeros_like(im)
cv2.drawContours(cimg, hulls, contour_idx, color=255, thickness=-1)
pts = np.array(np.where(cimg == 255)).T
ret.append(pts)
return ret
def _get_contours(self):
# find contours
_, self._contours, _ = cv2.findContours(self._frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
def find_digits(binary_img):
inv = cv2.bitwise_not(binary_img)
contours, hierarchy = cv2.findContours(inv,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1)
digits = []
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 500:
[x, y, w, h] = cv2.boundingRect(cnt)
margin = 20
x -= margin
y -= margin
w += margin*2
h += margin*2
figure = binary_img[y: y + h, x: x + w]
if figure.size > 0:
digits.append({
'image': figure,
'x': x,
'y': y,
'w': w,
'h': h,
})
return digits
def extractRoi(image, winSize, stepSize):
# hue boundaries
colors = [
(15, 30) # orange-yellow
]
mask, weight_map, mask_scale = roiMask(image, colors)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
yield weight_map, mask_scale
for resized in pyramid(image, winSize):
scale = image.shape[0] / resized.shape[0]
for x, y, w, h in boundingRects(mask_scale, contours):
x /= scale
y /= scale
w /= scale
h /= scale
center = (min(x + w / 2, resized.shape[1]), min(y + h / 2, resized.shape[0]))
if w > winSize[0] or h > winSize[1]:
for x, y, window in sliding_window(resized, (int(x), int(y), int(w), int(h)), stepSize, winSize):
yield ((x, y, winSize[0], winSize[1]), scale, window)
else:
x = max(0, int(center[0] - winSize[0] / 2))
y = max(0, int(center[1] - winSize[1] / 2))
window = resized[y:y + winSize[1], x:x + winSize[0]]
yield ((x, y, winSize[0], winSize[1]), scale, window)
def contour_plot_on_text_in_image(inv_img):
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 2))
dilated = cv2.dilate(inv_img, kernel, iterations=7) # dilate
_, contours, hierarchy = cv2.findContours(
dilated,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE) # get contours
return contours
def __find_contours(input, external_only):
"""Sets the values of pixels in a binary image to their distance to the nearest black pixel.
Args:
input: A numpy.ndarray.
external_only: A boolean. If true only external contours are found.
Return:
A list of numpy.ndarray where each one represents a contour.
"""
if(external_only):
mode = cv2.RETR_EXTERNAL
else:
mode = cv2.RETR_LIST
method = cv2.CHAIN_APPROX_SIMPLE
im2, contours, hierarchy =cv2.findContours(input, mode=mode, method=method)
return contours
def __find_contours(input, external_only):
"""Sets the values of pixels in a binary image to their distance to the nearest black pixel.
Args:
input: A numpy.ndarray.
external_only: A boolean. If true only external contours are found.
Return:
A list of numpy.ndarray where each one represents a contour.
"""
if(external_only):
mode = cv2.RETR_EXTERNAL
else:
mode = cv2.RETR_LIST
method = cv2.CHAIN_APPROX_SIMPLE
im2, contours, hierarchy =cv2.findContours(input, mode=mode, method=method)
return contours