完整的代码,实现了最小的矩形,圆形,随意矩形
来源
https://zhuanlan.zhihu.com/p/38739563
import cv2
import numpy as np
"""
REFER: https://hub.packtpub.com/opencv-detecting-edges-lines-shapes/
2018-06-30 Yonv1943
2018-07-01 comment to test.png
2018-07-01 gray in threshold, hierarchy
2018-07-01 draw_approx_hull_polygon() no [for loop]
2018-11-24
"""
def draw_contours(img, cnts): # conts = contours
img = np.copy(img)
img = cv2.drawContours(img, cnts, -1, (0, 255, 0), 2)
return img
def draw_min_rect_circle(img, cnts): # conts = contours
# img = np.copy(img)
img = np.zeros(img.shape, dtype=np.uint8)
for cnt in cnts:
x, y, w, h = cv2.boundingRect(cnt)
# cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
if w * h <= 16:
print(1)
for i in range(1, w):
for j in range(1, h):
print(x, y)
print(i, j)
img[x + i, y + j] = [0, 0, 0]
# print("success")
# msg1 = "定点x,y为" + str(x) + ' ' + str(y)
# msg2 = "长宽w,h为" + str(w) + " " + str(h)
# print(msg1)
# print(msg2)
# min_rect = cv2.minAreaRect(cnt) # min_area_rectangle
# min_rect = np.int0(cv2.boxPoints(min_rect))
# cv2.drawContours(img, [min_rect], 0, (0, 255, 0), 2) # green
#
# (x, y), radius = cv2.minEnclosingCircle(cnt)
# center, radius = (int(x), int(y)), int(radius) # center and radius of minimum enclosing circle
# img = cv2.circle(img, center, radius, (0, 0, 255), 2) # red
return img
def draw_approx_hull_polygon(img, cnts):
# img = np.copy(img)
cv2.drawContours(img, cnts, -1, (255, 0, 0), 2) # blue
min_side_len = img.shape[0] / 32 # 多边形边长的最小值 the minimum side length of polygon
min_poly_len = img.shape[0] / 16 # 多边形周长的最小值 the minimum round length of polygon
min_side_num = 3 # 多边形边数的最小值
approxs = [cv2.approxPolyDP(cnt, min_side_len, True) for cnt in cnts] # 以最小边长为限制画出多边形
approxs = [approx for approx in approxs if cv2.arcLength(approx, True) > min_poly_len] # 筛选出周长大于 min_poly_len 的多边形
approxs = [approx for approx in approxs if len(approx) > min_side_num] # 筛选出边长数大于 min_side_num 的多边形
# Above codes are written separately for the convenience of presentation.
cv2.polylines(img, approxs, True, (0, 255, 0), 2) # green
hulls = [cv2.convexHull(cnt) for cnt in cnts]
cv2.polylines(img, hulls, True, (0, 0, 255), 2) # red
# for cnt in cnts:
# cv2.drawContours(img, [cnt, ], -1, (255, 0, 0), 2) # blue
#
# epsilon = 0.02 * cv2.arcLength(cnt, True)
# approx = cv2.approxPolyDP(cnt, epsilon, True)
# cv2.polylines(img, [approx, ], True, (0, 255, 0), 2) # green
#
# hull = cv2.convexHull(cnt)
# cv2.polylines(img, [hull, ], True, (0, 0, 255), 2) # red
return img
def run():
image = cv2.imread('./dice2/001.jpg') # a black objects on white image is better
# print("三通道")
# print(image)
# print("单通道")
# print(image1)
# gray = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2GRAY)
# ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
thresh = cv2.Canny(image, 128, 256)
# thresh, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# print(hierarchy, ":hierarchy")
"""
[[[-1 -1 -1 -1]]] :hierarchy # cv2.Canny()
[[[ 1 -1 -1 -1]
[ 2 0 -1 -1]
[ 3 1 -1 -1]
[-1 2 -1 -1]]] :hierarchy # cv2.threshold()
"""
imgs = [
image, thresh,
draw_min_rect_circle(image, contours),
draw_approx_hull_polygon(image, contours),
]
# for img in imgs:
# cv2.imwrite("%s.jpg" % id(img), img)
img = draw_min_rect_circle(image, contours)
# cv2.imshow("contours", img)
cv2.imwrite('./x1.jpg', img)
cv2.waitKey(1943)
if __name__ == '__main__':
run()
pass
实现了边缘之外去噪声的(同学实现)
import cv2
import numpy as np
def draw_contours(img, cnts): # conts = contours
img = np.copy(img)
img = cv2.drawContours(img, cnts, -1, (0, 255, 0), 2)
return img
def draw_min_rect_circle(img, cnts): # conts = contours 你可以打印出contours出来看看坐标
img = np.copy(img)
height,width =img.shape[:2]
img2 = np.zeros((height,width))
for cnt in cnts:
x, y, w, h = cv2.boundingRect(cnt)
print(x,y,w,h)
if (w/h>1.5 or h/w>1.5) and (h>200 or w>200) :
img2[y:y+h,x:x+w] = img[y:y+h,x:x+w]
if (w / h < 1.5 or h / w < 1.5) and (h>500 or w>500):
img2[y:y + h, x:x + w] = img[y:y + h, x:x + w]
return img2
#021
image = cv2.imread('./yanmo_1/022.jpg',0)
thresh = cv2.Canny(image, 128, 256)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) ## contours是返回坐标
img = draw_min_rect_circle(image, contours)
cv2.imwrite('x22.jpg', img)
自己的弱智版实现
import cv2
import numpy as np
def draw_contours(img, cnts): # conts = contours
img = np.copy(img)
img = cv2.drawContours(img, cnts, -1, (0, 255, 0), 2)
return img
def draw_min_rect_circle(img, cnts): # conts = contours
for cnt in cnts:
x, y, w, h = cv2.boundingRect(cnt)
if w * h <= 16:
print(1)
for i in range(1, w):
for j in range(1, h):
print(x, y)
print(i, j)
img[x + i, y + j] = [0, 0, 0]
return img
def run():
image = cv2.imread('./dice2/001.jpg')
thresh = cv2.Canny(image, 128, 256)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
img = draw_min_rect_circle(image, contours)
cv2.imwrite('./x1.jpg', img)
cv2.waitKey(1943)
if __name__ == '__main__':
run()
pass