python cv2 源轮廓、近似轮廓、凸包、直边外接矩形、最小外接矩形、拟合直线

记录一些可能有用的图像处理方法,包括源轮廓、近似轮廓、凸包、直边外接矩形、最小外接矩形、拟合直线。

上述操作都是基于图像灰度图:

import cv2
import numpy as np

img = cv2.imread('./test.png')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

Rect_x = []
Rect_area = []

for cnt in contours:
	# 源轮廓
	cv2.drawContours(img, [cnt], -1, (0, 255, 0), 2)

	# 近似多边形, 轮廓近似,是Douglas-Peucker算法的一种实现方式
	# epsilon 为近似度参数,该值需要轮廓的周长信息
	# 多边形周长与源轮廓周长之比就是epsilon
	epsilon = 0.01 * cv2.arcLength(cnt,True)
	approx = cv2.approxPolyDP(cnt, epsilon, True)
	cv2.drawContours(img, [approx], -1, (255, 255, 0), 2)

	# 凸包
	hull = cv2.convexHull(cnt)
	cv2.drawContours(img, [hull], -1, (0, 0, 255), 2)

	#直边外接矩形
	x,y,w,h = cv2.boundingRect(cnt)
	area = w*h
	# 这里可以限制外接矩形大小,如果太小就不画出来。
	if w*h>200:
		print('x,y:', 'x', ',', 'y')
		Rect_x.append((x,y,w,h))
		Rect_area.append(area)
		cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

	# 最小外接矩形
	rect = cv2.minAreaRect(cnt)
	box = cv2.boxPoints(rect)
	box = np.int0(box)
	print(box)
	cv2.drawContours(img,[box],0,(0,0,255),2)
	# cv2.imwrite('./test_rect.png', img)

	# 拟合直线,这个还没有试过
	# rows,cols = img.shape[:2]
	# [vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
	# lefty = int((-x*vy/vx) + y)
	# righty = int(((cols-x)*vy/vx)+y)
	# cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)

cv2.imshow("test_image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值