python 生成任意形状的凸包图代码


Posted in Python onApril 16, 2020

一、效果图:

在左图的白色区域周围,画任意形状的凸包图。

python 生成任意形状的凸包图代码

二、代码

import cv2
import numpy as np
 
def generate_poly(image, n, area_thresh):
 """
 随机生成凸包
 :param image: 二值图
 :param n: 顶点个数
 :param area_thresh: 删除小于此面积阈值的凸包
 :return: 凸包图
 """
 row, col = np.where(image[:, :, 0] == 255) # 行,列
 point_set = np.zeros((n, 1, 2), dtype=int)
 for j in range(n):
  index = np.random.randint(0, len(row))
  point_set[j, 0, 0] = col[index]
  point_set[j, 0, 1] = row[index]
 hull = []
 hull.append(cv2.convexHull(point_set, False))
 drawing_board = np.zeros(image.shape, dtype=np.uint8)
 cv2.drawContours(drawing_board, hull, -1, (255, 255, 255), -1)
 cv2.namedWindow('drawing_board', 0), cv2.imshow('drawing_board', drawing_board), cv2.waitKey()
 
 # 如果生成面积过小,重新生成
 if cv2.contourArea(hull[0]) < area_thresh:
  drawing_board = generate_poly(image, n, area_thresh)
 
 # 如果生成洞,重新生成
 is_hole = image[drawing_board == 255] == 255
 if is_hole.all() == True: # 洞,则drawing_board所有为255的地方,image也是255,all()即为所有位置
  drawing_board = generate_poly(image, n, area_thresh)
 return drawing_board
 
 
img = np.zeros((256, 256, 3), np.uint8)
cv2.circle(img, (100, 100), 50, (255, 255, 255), -1)
cv2.namedWindow('img', 0), cv2.imshow('img', img), cv2.waitKey()
 
img_hull = generate_poly(img, 8, 100)
cv2.namedWindow('img_hull', 0), cv2.imshow('img_hull', img_hull), cv2.waitKey()

补充知识:opencv python 轮廓特征/凸包/外接矩形/外接圆/拟合矩形/拟合直线/拟合圆

Contour Features

1 图像的矩

cv2.moments()

图像的矩可以帮助计算物体的某些特征,如对象的质心,对象的区域等.

代码:

import cv2
import numpy as np
 
img = cv2.imread('img7.png',0)
ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)
 
cnt = contours[0]
M = cv2.moments(cnt)
print( M )

输出:

{'m00': 283.0, 'm10': 8260.666666666666, 'm01': 34747.666666666664, 'm20': 251349.8333333333, 'm11': 1008063.0, 'm02': 4274513.166666666, 'm30': 7941981.4, 'm21': 30484543.9, 'm12': 123258620.46666667, 'm03': 526819846.70000005, 'mu20': 10223.989595602674, 'mu11': -6208.702394974302, 'mu02': 8080.874165684916, 'mu30': 8302.495426246896, 'mu21': -14552.154961312423, 'mu12': 11791.528133469663, 'mu03': -3268.923251092434, 'nu20': 0.12765785058625623, 'nu11': -0.07752253611575, 'nu02': 0.10089867729257346, 'nu30': 0.006162296011483629, 'nu21': -0.010800931752771139, 'nu12': 0.008751933371317017, 'nu03': -0.0024262672459139235}

此刻,可以提取有用的数据,如面积,质心等.

质心由关系给出:

cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])

2轮廓面积

cv2.contourArea(contour[, oriented])

3轮廓周长

cv2.arcLength(curve, closed)

第二个参数指定形状是否为闭合轮廓

4轮廓近似

它根据我们指定的精度将轮廓形状近似为具有较少顶点数的另一个形状.它是Douglas-Peucker算法的一种实现方式.

cv2.approxPolyDP(curve, epsilon, closed[, approxCurve])

第二个参数epsilon,它是从轮廓到近似轮廓的最大距离.第三个参数指定曲线是否闭合.

下面,在第二幅图像中,绿线表示epsilon =弧长的10%的近似曲线. 第三幅图像显示相同的epsilon =弧长的1%.

代码:

import cv2
import numpy as np
 
img = cv2.imread('img8.png')
cv2.imshow('src',img)
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[1]
 
epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
cv2.polylines(img, [approx], True, (0, 0, 255), 2)
 
cv2.imshow('show',img)
cv2.waitKey()

python 生成任意形状的凸包图代码

5凸包

凸包看起来类似轮廓近似,但是它不是(两者在某些情况下可能提供相同的结果).

convexHull(points[, hull[, clockwise[, returnPoints]]]):检查曲线的凸性缺陷并进行修正.

points:传入的轮廓

hull:输出

clockwise:方向标志,如果为True,则顺时针方向输出凸包.

returnPoints:默认情况下为True,然后它返回hull points的坐标; 如果为False,则返回与hull points对应的轮廓点的索引

下面的手形图像. 红线表示手的凸包, 双面箭头标记显示凸起缺陷.

python 生成任意形状的凸包图代码

代码:

import cv2
import numpy as np
 
img = cv2.imread('img8.png')
 
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[1]
 
hull = cv2.convexHull(cnt)

returnPoints = True,得到以下值:

array([[[192, 135]],
  [[ 9, 135]],
  [[ 9, 12]],
  [[192, 12]]], dtype=int32)

如果想找到凸性缺陷,需要传递returnPoints = False,得到以下结果:

array([[129],
  [ 67],
  [ 0],
  [142]], dtype=int32)

这些是轮廓中相应点的索引,检查第一个值:

cnt[129]
Out[3]: array([[192, 135]], dtype=int32)

与第一个结果相同.

6 检查凸性

cv2.isContourConvex(contour):检查曲线是否凸起

7 外接矩形

7.1 直边外接矩形

它是一个直的矩形,它不考虑对象的旋转。因此,边界矩形的面积不会最小.

cv.boundingRect()

设(x,y)为矩形的左上角坐标,(w,h)为宽度和高度

代码:

import cv2
import numpy as np
 
img = cv2.imread('img7.png')
 
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
 
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
 
cv2.imshow('show',img)
cv2.waitKey()

python 生成任意形状的凸包图代码

7.2 最小外接矩形

cv.minAreaRect返回一个Box2D结构,其中包含以下detals - (center(x,y),(width,height),rotation of rotation)

cv.boxPoints画上述矩形.

代码:

rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)

python 生成任意形状的凸包图代码

8 最小封闭圈

(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
cv2.circle(img,center,radius,(0,255,0),2)

python 生成任意形状的凸包图代码

9 拟合椭圆

ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(img,ellipse,(0,255,0),2)

python 生成任意形状的凸包图代码

10 拟合直线

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)

python 生成任意形状的凸包图代码

以上这篇python 生成任意形状的凸包图代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
wxPython学习之主框架实例
Sep 28 Python
django开发教程之利用缓存文件进行页面缓存的方法
Nov 10 Python
python按综合、销量排序抓取100页的淘宝商品列表信息
Feb 24 Python
Python实现调用另一个路径下py文件中的函数方法总结
Jun 07 Python
详解Django解决ajax跨域访问问题
Aug 24 Python
在PyCharm中批量查找及替换的方法
Jan 20 Python
Python selenium根据class定位页面元素的方法
Feb 26 Python
python matplotlib画图库学习绘制常用的图
Mar 19 Python
Anaconda+vscode+pytorch环境搭建过程详解
May 25 Python
Opencv常见图像格式Data Type及代码实例
Nov 02 Python
python切片作为占位符使用实例讲解
Feb 17 Python
Python Matplotlib绘制动画的代码详解
May 30 Python
Python telnet登陆功能实现代码
Apr 16 #Python
基于python 凸包问题的解决
Apr 16 #Python
python实现交并比IOU教程
Apr 16 #Python
python 弧度与角度互转实例
Apr 15 #Python
使用Python三角函数公式计算三角形的夹角案例
Apr 15 #Python
Python selenium自动化测试模型图解
Apr 15 #Python
python简单实现最大似然估计&amp;scipy库的使用详解
Apr 15 #Python
You might like
在PHP中执行系统外部命令
2006/10/09 PHP
php中邮箱地址正则表达式实现与详解
2012/04/24 PHP
PHP 并发场景的几种解决方案
2019/06/14 PHP
laravel 多图上传及图片的存储例子
2019/10/14 PHP
juqery 学习之五 文档处理 插入
2011/02/11 Javascript
JavaScript instanceof 的使用方法示例介绍
2013/10/23 Javascript
JS版的date函数(和PHP的date函数一样)
2014/05/12 Javascript
require.js+vue开发微信上传图片组件
2016/10/27 Javascript
JavaScript Date 知识浅析
2017/01/29 Javascript
自制简易打赏功能的实例
2017/09/02 Javascript
ionic3+Angular4实现接口请求及本地json文件读取示例
2017/10/11 Javascript
轻松理解vue的双向数据绑定问题
2017/10/30 Javascript
Vue项目History模式404问题解决方法
2018/10/31 Javascript
微信小程序实现顶部下拉菜单栏
2018/11/04 Javascript
JS基于对象的链表实现与使用方法示例
2019/01/31 Javascript
监控Nodejs的性能实例代码
2019/07/02 NodeJs
Vue.js 实现地址管理页面思路详解(地址添加、编辑、删除和设置默认地址)
2019/12/11 Javascript
JavaScript中变量提升机制示例详解
2019/12/27 Javascript
简单了解JavaScript作用域
2020/07/31 Javascript
[40:55]DOTA2上海特级锦标赛主赛事日 - 2 败者组第二轮#4Newbee VS Fnatic
2016/03/03 DOTA
python编写暴力破解FTP密码小工具
2014/11/19 Python
简单了解python模块概念
2018/01/11 Python
一篇文章快速了解Python的GIL
2018/01/12 Python
python将每个单词按空格分开并保存到文件中
2018/03/19 Python
Python第三方库face_recognition在windows上的安装过程
2019/05/03 Python
Django生成PDF文档显示在网页上以及解决PDF中文显示乱码的问题
2019/07/04 Python
在Anaconda3下使用清华镜像源安装TensorFlow(CPU版)
2020/04/19 Python
美国狗旅行和户外用品领先供应商:kurgo
2020/08/18 全球购物
优秀中专生推荐信
2013/11/17 职场文书
淘宝客服自我总结鉴定
2014/01/25 职场文书
公安纪律作风整顿剖析材料
2014/10/10 职场文书
青年教师个人总结
2015/02/11 职场文书
2016年优秀共青团员事迹材料
2016/02/25 职场文书
Android开发之WECHAT微信小程序路由跳转的两种形式
2022/04/12 Java/Android
苹果的回收机器人可以通过拆解iPhone获取大量的金和铜并外公布了环境保护最新进展
2022/04/21 数码科技
使用CSS实现百叶窗效果示例代码
2023/05/07 HTML / CSS