Article / 文章中心

实战 | OpenCV如何将不同轮廓合并成一个轮廓(附源码)

发布时间:2022-08-23 点击数:1180

导读

本文主要介绍如何用OpenCV将不同的轮廓合并成一个轮廓的实现方法和代码演示。

背景介绍

图像处理的应用场景中常常会遇到一种情况,本来是一个整体的目标,因为不同的亮度或其他原因导致它分割成多个部分,这种情况在用OpenCV处理的时候会被当成多个轮廓(如下图所示),那么遇到这种情况,我们如何把不同的轮廓合并成一个轮廓,然后做后续的处理呢?

实现方法与步骤

这里我们不用上面的绘画图,而是使用下面这张图做演示:

我们的目的:将上图中的文字轮廓看成一个整体,然后求其最小外接矩形,获得角度,将文字旋转水平,后续可以做简单的文字识别

【1】先提取文字部分轮廓(S通道阈值处理)

hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV)
H,S,V = cv2.split(hsvImg)
ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)

 

hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV) H,S,V = cv2.split(hsvImg) ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)

【2】中值滤波去除小杂讯

blurImg = cv2.medianBlur(thresImg,5)
cv2.imshow('blur', blurImg)

 

【3】查找轮廓计算轮廓最小外接矩形

contours,hierarchy = cv2.findContours(blurImg, 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)

 

hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV) H,S,V = cv2.split(hsvImg) ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)

【4】轮廓合并成一个绘制最小外接矩形

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,(0,255,0),2)

完整代码与效果:

import numpy as np
import cv2

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(blurImg, 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,(0,255,0),2)
cv2.imshow('merge_res', merge_res)
cv2.imwrite('merge_res.jpg', merge_res)

# 记录结束时间   
end = cv2.getTickCount()
# 运行耗时
use_time = (end - start) / cv2.getTickFrequency()
print('use-time: %.3fs' % use_time)

cv2.waitKey(0)
cv2.destroyAllWindows()
print ('finish')