python opencv合并轮廓

python opencv合并轮廓_第1张图片 

 



import cv2

import cv2
import numpy as np

# 创建一个黑色图像
img = np.zeros((500, 500), dtype=np.uint8)

# 创建轮廓
contours = [
    np.array([[50, 50], [100, 50], [100, 100], [50, 100]]),
    np.array([[150, 150], [200, 150], [200, 200], [150, 200]])
]

# 绘制轮廓
cv2.drawContours(img, contours, -1, 255, -1)

# 显示结果
cv2.imshow('Binary image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.imwrite('A.jpg',img)
merge_res = img.copy()#显示合并后轮廓结构
split_res = img.copy()#显示合并后轮廓结构
src = cv2.imread('A.jpg')
#
cv2.imshow('src', src)
#
split_res = src.copy()#显示每个轮廓结构
#
merge_res = src.copy()#显示合并后轮廓结构

# 记录开始时间

# start = cv2.getTickCount()
#
# hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV)
#
# H,S,V = cv2.split(hsvImg)
#
# ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)
#
# cv2.imshow('threshold', thresImg)
#
# blurImg = cv2.medianBlur(thresImg,5)
#
# cv2.imshow('blur', blurImg)

contours,hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

merge_list = []

for cnt in contours:

   rect = cv2.minAreaRect(cnt)

   box = cv2.boxPoints(rect)

   box = np.int0(box)

   split_res = cv2.drawContours(split_res,[box],0,(0,0,255),2)

   merge_list.append(cnt)

cv2.imshow('split_res', split_res)

cv2.imwrite('split_res.jpg', split_res)

contours_merge = np.vstack([merge_list[0],merge_list[1]])

for i in range(2, len(merge_list)):

  contours_merge = np.vstack([contours_merge,merge_list[i]])

rect2 = cv2.minAreaRect(contours_merge)

box2 = cv2.boxPoints(rect2)

box2 = np.int0(box2)

merge_res = cv2.drawContours(merge_res,[box2],0,(255,255,255),2)

cv2.imshow('merge_res', merge_res)

cv2.imwrite('merge_res.jpg', merge_res)

# 记录结束时间 end = cv2.getTickCount()

# 运行耗时 use_time = (end - start) / cv2.getTickFrequency()


cv2.waitKey(0)

# cv2.destroyAllWindows()

print ('finish')

你可能感兴趣的:(python基础,opencv,计算机视觉,python)