1、需求描述
给一张图片,找出其轮廓,并画出轮廓的上下左右极值点
输入图片
输出效果
2、功能实现
# 导入必要的包
import imutils
import cv2
# 加载图像,将其转换为灰度,并稍微模糊
image = cv2.imread("6.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray.jpg", gray)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
cv2.imwrite("GaussianBlur.jpg", gray)
# 对图像设置阈值,然后执行一系列腐蚀 + 膨胀以去除任何小的噪声区域
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite("thresh.jpg", thresh)
腐蚀一下
thresh = cv2.erode(thresh, None, iterations=2)
cv2.imwrite("erode.jpg", thresh)
thresh = cv2.dilate(thresh, None, iterations=2)
cv2.imwrite("dilate.jpg", thresh)
# 在阈值图像中找到轮廓,然后获取最大的一个
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)
# 确定轮廓的极值点
extLeft = tuple(c[c[:, :, 0].argmin()][0])
extRight = tuple(c[c[:, :, 0].argmax()][0])
extTop = tuple(c[c[:, :, 1].argmin()][0])
extBot = tuple(c[c[:, :, 1].argmax()][0])
# 画出物体的轮廓,然后画出每个极值点,最左边是红色,最右边是绿色,最上面是蓝色,最下面是青色
cv2.drawContours(image, [c], -1, (0, 255, 255), 2)
cv2.circle(image, extLeft, 8, (0, 0, 255), -1)
cv2.circle(image, extRight, 8, (0, 255, 0), -1)
cv2.circle(image, extTop, 8, (255, 0, 0), -1)
cv2.circle(image, extBot, 8, (255, 255, 0), -1)
# 显示输出图像
cv2.imshow("Image", image)
cv2.imwrite("result.jpg", image)
cv2.waitKey(0)
3、更多的例子
输入
输出
输入
输出
只画面积最大的轮廓
输入图片
输出图片
输入图片
输出图片
去掉了腐蚀和膨胀操作,才能分割出来完整的树叶
输入图片
输出图片
注意到均为黑色背景,从第二小节详细实现来看,也能知道,白色背景效果直接扑街
4、完整代码
# 导入必要的包
import imutils
import cv2
# 加载图像,将其转换为灰度,并稍微模糊
image = cv2.imread("6.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray.jpg", gray)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
cv2.imwrite("GaussianBlur.jpg", gray)
# 对图像设置阈值,然后执行一系列腐蚀 + 膨胀以去除任何小的噪声区域
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite("thresh.jpg", thresh)
thresh = cv2.erode(thresh, None, iterations=2)
cv2.imwrite("erode.jpg", thresh)
thresh = cv2.dilate(thresh, None, iterations=2)
cv2.imwrite("dilate.jpg", thresh)
# 在阈值图像中找到轮廓,然后获取最大的一个
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)
# 确定轮廓的极值点
extLeft = tuple(c[c[:, :, 0].argmin()][0])
extRight = tuple(c[c[:, :, 0].argmax()][0])
extTop = tuple(c[c[:, :, 1].argmin()][0])
extBot = tuple(c[c[:, :, 1].argmax()][0])
# 画出物体的轮廓,然后画出每个极值点,最左边是红色,最右边是绿色,最上面是蓝色,最下面是青色
cv2.drawContours(image, [c], -1, (0, 255, 255), 2)
cv2.circle(image, extLeft, 8, (0, 0, 255), -1)
cv2.circle(image, extRight, 8, (0, 255, 0), -1)
cv2.circle(image, extTop, 8, (255, 0, 0), -1)
cv2.circle(image, extBot, 8, (255, 255, 0), -1)
# 显示输出图像
cv2.imshow("Image", image)
cv2.imwrite("result.jpg", image)
cv2.waitKey(0)