#1 获取轮廓
OpenCV2获取轮廓主要是用cv2.findContours

import numpy as np
import cv2

image = cv2.imread('test.jpg')
imgray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
#image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 旧版本返回三个参数,新版本返回2个
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

其中,findContours的第二个函数很重要,主要分为 cv2.RETR_LIST, cv2.RETR_TREE, cv2.RETR_CCOMP, cv2.RETR_EXTERNAL,具体含义可参考官方文档

#2 画出轮廓
为了看到自己画了哪些轮廓,可以使用 cv2.boundingRect()函数获取轮廓的范围,即左上角原点,以及他的高和宽。然后用cv2.rectangle()方法画出矩形轮廓

for i in range(0,len(contours)):  
	x, y, w, h = cv2.boundingRect(contours[i])   
	cv2.rectangle(image, (x,y), (x+w,y+h), (153,153,0), 5) 

#3 切割轮廓
轮廓的切割主要是通过数组切片实现的,不过这里有一个小技巧:就是图片切割的w,h是宽和高,而数组讲的是行(row)和列(column)
所以,在切割图片时,数组的高和宽是反过来写的

   newimage=image[y+2:y+h-2,x+2:x+w-2] # 先用y确定高,再用x确定宽
   nrootdir=("E:/cut_image/")
   if not os.path.isdir(nrootdir):
       os.makedirs(nrootdir)
   cv2.imwrite( nrootdir+str(i)+".jpg",newimage) 
   print (i)

这样就可以把确定的轮廓都切割出来了。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐