def find_contours(mask, smooth_factor=0.005):
""" Find the contours in a given mask """
border = 5
# Canny detection breaks down with the edge of the image
my_mask = cv2.copyMakeBorder(mask, border, border, border, border,
cv2.BORDER_CONSTANT, value=(0, 0, 0))
my_mask = cv2.cvtColor(my_mask, cv2.COLOR_BGR2GRAY)
if is_cv2():
contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
else:
_, contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# shift the contours back down
for contour in contours:
for pnt in contour:
if pnt[0][1] > border:
pnt[0][1] = pnt[0][1] - border
else:
pnt[0][1] = 0
if pnt[0][0] > border:
pnt[0][0] = pnt[0][0] - border
else:
pnt[0][0] = 0
closed_contours = []
for contour in contours:
epsilon = smooth_factor*cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
area = cv2.contourArea(approx)
# if they are too small they are not edges
if area < 200:
continue
closed_contours.append(approx)
return closed_contours
python类findContours()的实例源码
def find_components(im, max_components=16):
"""Dilate the image until there are just a few connected components.
Returns contours for these components."""
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10))
dilation = dilate(im, kernel, 6)
count = 21
n = 0
sigma = 0.000
while count > max_components:
n += 1
sigma += 0.005
result = cv2.findContours(dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(result) == 3:
_, contours, hierarchy = result
elif len(result) == 2:
contours, hierarchy = result
possible = find_likely_rectangles(contours, sigma)
count = len(possible)
return (dilation, possible, n)
find_rect_and_transform.py 文件源码
项目:quadrilaterals-rectifier
作者: michal2229
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def extract_rect(im):
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# finding contour with max area
largest = None
for cnt in contours:
if largest == None or cv2.contourArea(cnt) > cv2.contourArea(largest):
largest = cnt
peri = cv2.arcLength(largest, True)
appr = cv2.approxPolyDP(largest, 0.02 * peri, True)
#cv2.drawContours(im, appr, -1, (0,255,0), 3)
points_list = [[i[0][0], i[0][1]] for i in appr]
left = sorted(points_list, key = lambda p: p[0])[0:2]
right = sorted(points_list, key = lambda p: p[0])[2:4]
print("l " + str(left))
print("r " + str(right))
lu = sorted(left, key = lambda p: p[1])[0]
ld = sorted(left, key = lambda p: p[1])[1]
ru = sorted(right, key = lambda p: p[1])[0]
rd = sorted(right, key = lambda p: p[1])[1]
print("lu " + str(lu))
print("ld " + str(ld))
print("ru " + str(ru))
print("rd " + str(rd))
lu_ = [ (lu[0] + ld[0])/2, (lu[1] + ru[1])/2 ]
ld_ = [ (lu[0] + ld[0])/2, (ld[1] + rd[1])/2 ]
ru_ = [ (ru[0] + rd[0])/2, (lu[1] + ru[1])/2 ]
rd_ = [ (ru[0] + rd[0])/2, (ld[1] + rd[1])/2 ]
print("lu_ " + str(lu_))
print("ld_ " + str(ld_))
print("ru_ " + str(ru_))
print("rd_ " + str(rd_))
src_pts = np.float32(np.array([lu, ru, rd, ld]))
dst_pts = np.float32(np.array([lu_, ru_, rd_, ld_]))
h,w,b = im.shape
H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
print("H" + str(H))
imw = cv2.warpPerspective(im, H, (w, h))
return imw[lu_[1]:rd_[1], lu_[0]:rd_[0]] # cropping image
def recognize_text(original):
idcard = original
gray = cv2.cvtColor(idcard, cv2.COLOR_BGR2GRAY)
# Morphological gradient:
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opening = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, kernel)
# Binarization
ret, binarization = cv2.threshold(opening, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# Connected horizontally oriented regions
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(binarization, cv2.MORPH_CLOSE, kernel)
# find countours
_, contours, hierarchy = cv2.findContours(
connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE
)
return contours, hierarchy
def find_components(edges, max_components=16):
"""Dilate the image until there are just a few connected components.
Returns contours for these components."""
# Perform increasingly aggressive dilation until there are just a few
# connected components.
count = 21
dilation = 5
n = 1
while count > 16:
n += 1
dilated_image = dilate(edges, N=3, iterations=n)
_, contours, hierarchy = cv2.findContours(dilated_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
count = len(contours)
#print dilation
#Image.fromarray(edges).show()
#Image.fromarray(255 * dilated_image).show()
return contours
def _find_size_candidates(self, image):
binary_image = self._filter_image(image)
_, contours, _ = cv2.findContours(binary_image,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
size_candidates = []
for contour in contours:
bounding_rect = cv2.boundingRect(contour)
contour_area = cv2.contourArea(contour)
if self._is_valid_contour(contour_area, bounding_rect):
candidate = (bounding_rect[2] + bounding_rect[3]) / 2
size_candidates.append(candidate)
return size_candidates
def camera_gesture_trigger():
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
ret,thresh1 = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
max_area=0
for i in range(len(contours)):
cnt=contours[i]
area = cv2.contourArea(cnt)
if(area>max_area):
max_area=area
ci=i
cnt=contours[ci]
hull = cv2.convexHull(cnt)
moments = cv2.moments(cnt)
cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)
if defects is not None:
if defects.shape[0] >= 5:
return 1
return 0
def get_largest(im, n):
# Find contours of the shape
major = cv2.__version__.split('.')[0]
if major == '3':
_, contours, _ = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
else:
contours, _ = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Cycle through contours and add area to array
areas = []
for c in contours:
areas.append(cv2.contourArea(c))
# Sort array of areas by size
sorted_areas = sorted(zip(areas, contours), key=lambda x: x[0], reverse=True)
if sorted_areas and len(sorted_areas) >= n:
# Find nth largest using data[n-1][1]
return sorted_areas[n - 1][1]
else:
return None
Artificial-potential-without-controller.py 文件源码
项目:Artificial-Potential-Field
作者: vampcoder
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def classify(img):
cimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img2 = cv2.medianBlur(cimg, 13)
ret, thresh1 = cv2.threshold(cimg, 100, 120, cv2.THRESH_BINARY)
t2 = copy.copy(thresh1)
x, y = thresh1.shape
arr = np.zeros((x, y, 3), np.uint8)
final_contours = []
image, contours, hierarchy = cv2.findContours(t2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#cv2.imshow('image', image)
#k = cv2.waitKey(0)
for i in range(len(contours)):
cnt = contours[i]
if cv2.contourArea(cnt) > 35000 and cv2.contourArea(cnt) < 15000:
cv2.drawContours(img, [cnt], -1, [0, 255, 255])
cv2.fillConvexPoly(arr, cnt, [255, 255, 255])
final_contours.append(cnt)
cv2.imshow('arr', arr)
k = cv2.waitKey(0)
return arr
def get_image_xy_corner(self):
"""get ?artesian coordinates from raster"""
import cv2
if not self.image_path:
return False
image_xy_corners = []
img = cv2.imread(self.image_path, cv2.IMREAD_GRAYSCALE)
imagem = (255 - img)
try:
ret, thresh = cv2.threshold(imagem, 10, 128, cv2.THRESH_BINARY)
try:
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
except Exception:
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = hierarchy[0]
hierarhy_contours = [[] for _ in range(len(hierarchy))]
for fry in range(len(contours)):
currentContour = contours[fry]
currentHierarchy = hierarchy[fry]
cc = []
# epsilon = 0.0005 * cv2.arcLength(contours[len(contours) - 1], True)
approx = cv2.approxPolyDP(currentContour, self.epsilon, True)
if len(approx) > 2:
for c in approx:
cc.append([c[0][0], c[0][1]])
parent_index = currentHierarchy[3]
index = fry if parent_index < 0 else parent_index
hierarhy_contours[index].append(cc)
image_xy_corners = [c for c in hierarhy_contours if len(c) > 0]
return image_xy_corners
except Exception as ex:
self.error(ex)
return image_xy_corners
def _detect_bot(self, hsv_image):
BOT_MIN = np.array([28,8,100], np.uint8)
BOT_MAX = np.array([32,255,255], np.uint8)
thresholded_image = cv2.inRange(hsv_image, BOT_MIN, BOT_MAX)
thresholded_image = cv2.medianBlur(thresholded_image, 15)
_, contours, hierarchy = cv2.findContours(thresholded_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
(bot_x, bot_y) = (-1000,-1000)
else:
bot = contours[0]
M = cv2.moments(bot)
if len(bot) > 2:
bot_x = int(M['m10']/M['m00'])
bot_y = int(M['m01']/M['m00'])
else:
(bot_x, bot_y) = (-1000,-1000)
return thresholded_image, (bot_x, bot_y)
def remove_blobs(image, min_area=0, max_area=sys.maxsize, threshold=128,
method='8-connected', return_mask=False):
"""Binarize image using threshold, and remove (turn into black)
blobs of connected pixels of white of size bigger or equal than
min_area but smaller or equal than max_area from the original image,
returning it afterward."""
method = method.lower()
if method == '4-connected':
method = cv2.LINE_4
elif method in ('16-connected', 'antialiased'):
method = cv2.LINE_AA
else: # 8-connected
method = cv2.LINE_8
mono_image = binarize_image(image, method='boolean', threshold=threshold)
_, all_contours, _ = cv2.findContours(mono_image, cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
contours = np.array([contour for contour in all_contours
if min_area <= cv2.contourArea(contour) <= max_area])
mask = np.ones(mono_image.shape, np.uint8)
cv2.drawContours(mask, contours, -1, 0, -1, lineType=method)
return image, 255 * mask
def contourImg(image):
#Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them
_, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#The contouring operation does some weird stuff to the image so this line just fills the whole thing with black
image.fill(0)
boundingRect = []
#Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing
for j in [i for i in contours if cv2.contourArea(i) > minArea]:
#br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner
br = cv2.boundingRect(j)
if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol):
boundingRect.append(br)
for x in range(0, len(boundingRect)):
for y in range(x+1, len(boundingRect)):
i = boundingRect[x]
j = boundingRect[y]
if(abs(i[1]-j[1]) < i[3]/2) and abs(abs(i[0]-j[0])/i[1] - GRPASPECT) < grpAspectTol:
return [createRectCnt(i), createRectCnt(j)]
return None
def diagContour(image):
#Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them
_, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#The contouring operation does some weird stuff to the image so this line just fills the whole thing with black
image.fill(0)
boundingRect = []
firstFail = []
#Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing
for j in [i for i in contours if cv2.contourArea(i) > minArea]:
#br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner
br = cv2.boundingRect(j)
if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol):
boundingRect.append(br)
else:
firstFail.append([br, br[2]/br[3], cv2.contourArea(j)/(br[2]*br[3])])
secondRound = []
for x in range(0, len(boundingRect)):
for y in range(x+1, len(boundingRect)):
i = boundingRect[x]
j = boundingRect[y]
secondRound.append([(x,y,i,j), (abs(i[1]-j[1]), i[3]/2), abs(i[0]-j[0])/i[1]])
for x in secondRound:
if(x[1][0] < x[1][1] and x[2] - GRPASPECT < grpAspectTol):
return firstFail, secondRound, [createRectCnt(x[0][2]), createRectCnt(x[0][3])]
return firstFail, secondRound, None
def plateDetect(img,img2):
'''?????????????????'''
im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for con in contours:
x,y,w,h=cv2.boundingRect(con)
area=w*h
ratio=w/h
if ratio>2 and ratio<4 and area>=2000 and area<=25000:
logo_y1=max(0,int(y-h*3.0))
logo_y2=y
logo_x1=x
logo_x2=x+w
img_logo=img2.copy()
logo=img_logo[logo_y1:logo_y2,logo_x1:logo_x2]
cv2.imwrite('./logo1.jpg',logo)
cv2.rectangle(img2,(x,y),(x+w,y+h),(255,0,0),2)
cv2.rectangle(img2,(logo_x1,logo_y1),(logo_x2,logo_y2),(0,255,0),2)
global plate
plate=[x,y,w,h]
#?????????
return logo
def logoDetect(img,imgo):
'''???????????????'''
imglogo=imgo.copy()
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img=cv2.resize(img,(2*img.shape[1],2*img.shape[0]),interpolation=cv2.INTER_CUBIC)
#img=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,-3)
ret,img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
#img=cv2.Sobel(img, cv2.CV_8U, 1, 0, ksize = 9)
img=cv2.Canny(img,100,200)
element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
img = cv2.dilate(img, element2,iterations = 1)
img = cv2.erode(img, element1, iterations = 3)
img = cv2.dilate(img, element2,iterations = 3)
#????
im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
tema=0
result=[]
for con in contours:
x,y,w,h=cv2.boundingRect(con)
area=w*h
ratio=max(w/h,h/w)
if area>300 and area<20000 and ratio<2:
if area>tema:
tema=area
result=[x,y,w,h]
ratio2=ratio
#?????????????????,??????????
logo2_X=[int(result[0]/2+plate[0]-3),int(result[0]/2+plate[0]+result[2]/2+3)]
logo2_Y=[int(result[1]/2+max(0,plate[1]-plate[3]*3.0)-3),int(result[1]/2+max(0,plate[1]-plate[3]*3.0)+result[3]/2)+3]
cv2.rectangle(img,(result[0],result[1]),(result[0]+result[2],result[1]+result[3]),(255,0,0),2)
cv2.rectangle(imgo,(logo2_X[0],logo2_Y[0]),(logo2_X[1],logo2_Y[1]),(0,0,255),2)
print tema,ratio2,result
logo2=imglogo[logo2_Y[0]:logo2_Y[1],logo2_X[0]:logo2_X[1]]
cv2.imwrite('./logo2.jpg',logo2)
return img
def apply(self, item, threshold):
img = item.img_mat
img[img > 0] = 255
_, contours, _ = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
valid_contours = []
for contour in contours:
max_x = contour[:, :, 0].max()
min_x = contour[:, :, 0].min()
max_y = contour[:, :, 1].max()
min_y = contour[:, :, 1].min()
if (max_x - min_x) * (max_y - min_y) > threshold:
valid_contours.append(contour)
yield valid_contours
def find_components(edges, max_components=16):
"""Dilate the image until there are just a few connected components.
Returns contours for these components."""
# Perform increasingly aggressive dilation until there are just a few
# connected components.
count = 21
dilation = 5
n = 1
while count > 16:
n += 1
dilated_image = dilate(edges, N=3, iterations=n)
contours, hierarchy = cv2.findContours(dilated_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
count = len(contours)
#print dilation
#Image.fromarray(edges).show()
#Image.fromarray(255 * dilated_image).show()
return contours
def findContours(arg_img,arg_canvas, arg_MinMaxArea=False, arg_debug= False):
image= arg_img.copy()
#print image
canvas= arg_canvas.copy()
if len(image)==3:
image = cv2.cvtColor(self.image, cv2.COLOR_GRAY2BGR)
if sys.version_info.major == 2:
ctrs, hier = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
else:
_, ctrs, hier = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if arg_MinMaxArea is not False:
ctrs = filter(lambda x : arg_MinMaxArea[1]> cv2.contourArea(x) > arg_MinMaxArea[0] , ctrs)
print '>>> ', len(ctrs)
for ctr in ctrs:
print 'Area: ', cv2.contourArea(ctr)
cv2.drawContours(canvas, [ctr], 0, (0, 128, 255), 3)
if arg_debug:
cv2.imwrite('Debug/debug_findContours.jpg',canvas)
return canvas
def get_contour(self, arg_frame, arg_export_index, arg_export_path, arg_export_filename, arg_binaryMethod):
# Otsu's thresholding after Gaussian filtering
tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(tmp,(5,5),0)
if arg_binaryMethod== 0:
ret, thresholdedImg= cv2.threshold(blur.copy() , self.threshold_graylevel, 255 , 0)
elif arg_binaryMethod == 1:
ret,thresholdedImg = cv2.threshold(blur.copy(),0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
elif arg_binaryMethod== 2:
thresholdedImg = cv2.adaptiveThreshold(blur.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,0)
result = cv2.cvtColor(thresholdedImg, cv2.COLOR_GRAY2RGB)
ctrs, hier = cv2.findContours(thresholdedImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ctrs = filter(lambda x : cv2.contourArea(x) > self.threshold_size , ctrs)
rects = [[cv2.boundingRect(ctr) , ctr] for ctr in ctrs]
for rect , cntr in rects:
cv2.drawContours(result, [cntr], 0, (0, 128, 255), 3)
if arg_export_index:
cv2.imwrite(arg_export_path+ arg_export_filename+'.jpg', result)
print "Get Contour success"
return result