Python OpenCV实现测量图片物体宽度


Posted in Python onMay 27, 2020

一、 题目描述

测量所给图片的高度,即上下边缘间的距离。

Python OpenCV实现测量图片物体宽度

思路:

  • 将图片进行阈值操作得到二值化图片。
  • 截取只包含上下边框的部分,以便于后续的轮廓提取
  • 轮廓检测
  • 得到结果

二、 实现过程

1.用于给图片添加中文字符

#用于给图片添加中文字符
def ImgText_CN(img, text, left, top, textColor=(0, 255, 0), textSize=20):
  if (isinstance(img, np.ndarray)): #判断是否为OpenCV图片类型
    img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  draw = ImageDraw.Draw(img)
  fontText = ImageFont.truetype(r'C:\Windows\Fonts\simsun.ttc', textSize, encoding="utf-8")     ##中文字体
  draw.text((left, top), text, textColor, font=fontText)   #写文字
  return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

2.实现图片反色功能

#实现图片反色功能
def PointInvert(img):
  height, width = img.shape    #获取图片尺寸
  for i in range(height):
    for j in range(width):
      pi = img[i, j]
      img[i, j] = 255 - pi
  return img

3.边缘检测

# canny边缘检测
edges = cv2.Canny(th, 30, 70) 
res=PointInvert(edges)              #颜色反转
#显示图片
cv2.imshow('original', th)            #显示二值化后的图,主题为白色,背景为黑色 更加容易找出轮廓
key = cv2.waitKey(0)
if key==27: #按esc键时,关闭所有窗口
  print(key)
  cv2.destroyAllWindows()

4.轮廓操作

contours, hierarchy = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)    #得到轮廓

cnt = contours[0]        #取出轮廓

x, y, w, h = cv2.boundingRect(cnt)     #用一个矩形将轮廓包围

img_gray = cv2.cvtColor(res, cv2.COLOR_GRAY2BGR)        #将灰度转化为彩色图片方便画图

cv2.line(img_gray, (x, y), (x + w, y), (0,0,255), 2, 5)     #上边缘
cv2.line(img_gray, (x, y+h), (x + w, y+h), (0, 0, 255), 2, 5)  #下边缘

img1[80:230, 90:230] = img_gray     #用带有上下轮廓的图替换掉原图的对应部分

5.显示图片

res1=ImgText_CN(img1, '宽度%d'%h, 25, 25, textColor=(0, 255, 0), textSize=30)  #绘制文字
#显示图片 
cv2.imshow('original', res1)
key = cv2.waitKey(0)
if key==27: #按esc键时,关闭所有窗口
  print(key)
  cv2.destroyAllWindows()

6.完整代码

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

#用于给图片添加中文字符
def ImgText_CN(img, text, left, top, textColor=(0, 255, 0), textSize=20):
  if (isinstance(img, np.ndarray)): #判断是否为OpenCV图片类型
    img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  draw = ImageDraw.Draw(img)
  fontText = ImageFont.truetype(r'C:\Windows\Fonts\simsun.ttc', textSize, encoding="utf-8")     ##中文字体
  draw.text((left, top), text, textColor, font=fontText)   #写文字
  return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

#实现图片反色功能
def PointInvert(img):
  height, width = img.shape    #获取图片尺寸
  for i in range(height):
    for j in range(width):
      pi = img[i, j]
      img[i, j] = 255 - pi
  return img



img=cv2.imread("gongjian1.bmp",0)        #加载彩色图
img1=cv2.imread("gongjian1.bmp",1)        #加载灰度图

recimg = img[80:230, 90:230]          #截取需要的部分
img2 = img1[80:230, 90:230]           #截取需要的部分
ret, th = cv2.threshold(recimg, 90, 255, cv2.THRESH_BINARY)     #阈值操作二值化


# canny边缘检测
edges = cv2.Canny(th, 30, 70) 
res=PointInvert(edges)              #颜色反转
#显示图片
cv2.imshow('original', th)            #显示二值化后的图,主题为白色,背景为黑色 更加容易找出轮廓
key = cv2.waitKey(0)
if key==27: #按esc键时,关闭所有窗口
  print(key)
  cv2.destroyAllWindows()
  
contours, hierarchy = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)    #得到轮廓

cnt = contours[0]        #取出轮廓

x, y, w, h = cv2.boundingRect(cnt)     #用一个矩形将轮廓包围

img_gray = cv2.cvtColor(res, cv2.COLOR_GRAY2BGR)        #将灰度转化为彩色图片方便画图

cv2.line(img_gray, (x, y), (x + w, y), (0,0,255), 2, 5)     #上边缘

cv2.line(img_gray, (x, y+h), (x + w, y+h), (0, 0, 255), 2, 5)  #下边缘
img1[80:230, 90:230] = img_gray                 #用带有上下轮廓的图替换掉原图的对应部分

res1=ImgText_CN(img1, '宽度%d'%h, 25, 25, textColor=(0, 255, 0), textSize=30)  #绘制文字
#显示图片 
cv2.imshow('original', res1)
key = cv2.waitKey(0)
if key==27: #按esc键时,关闭所有窗口
  print(key)
  cv2.destroyAllWindows()

三、 运行结果(效果)

Python OpenCV实现测量图片物体宽度

Python OpenCV实现测量图片物体宽度

四、 问题及解决方法

红色轮廓没有显示,解决方案:将灰度图转化为彩色图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python函数返回多个值的示例方法
Dec 04 Python
使用Python的PEAK来适配协议的教程
Apr 14 Python
Python的标准模块包json详解
Mar 13 Python
python与C互相调用的方法详解
Jul 14 Python
python字典DICT类型合并详解
Aug 17 Python
用Python进行简单图像识别(验证码)
Jan 19 Python
在PyCharm中批量查找及替换的方法
Jan 20 Python
python简单鼠标自动点击某区域的实例
Jun 25 Python
django表单的Widgets使用详解
Jul 22 Python
解决python 3 urllib 没有 urlencode 属性的问题
Aug 22 Python
利用pandas将非数值数据转换成数值的方式
Dec 18 Python
python 实现人和电脑猜拳的示例代码
Mar 02 Python
Python中socket网络通信是干嘛的
May 27 #Python
Python中SQLite如何使用
May 27 #Python
Pycharm插件(Grep Console)自定义规则输出颜色日志的方法
May 27 #Python
Python中如何引入第三方模块
May 27 #Python
Python中的wordcloud库安装问题及解决方法
May 27 #Python
Python Dataframe常见索引方式详解
May 27 #Python
Python代码中如何读取键盘录入的值
May 27 #Python
You might like
PHP提取中文首字母
2008/04/09 PHP
PHP中函数内引用全局变量的方法
2008/10/20 PHP
提高PHP编程效率的53个要点(经验小结)
2010/09/04 PHP
YII实现分页的方法
2014/07/09 PHP
php简单实现发送带附件的邮件
2015/06/10 PHP
飞鱼(shqlsl) javascript作品集
2006/12/16 Javascript
JS 文件传参及处理技巧分析
2010/05/13 Javascript
jquery json 实例代码
2010/12/02 Javascript
js之事件冒泡和事件捕获详细介绍
2013/10/28 Javascript
jQuery 实现自动填充邮箱功能(带下拉提示)
2014/10/14 Javascript
jQuery中slice()方法用法实例
2015/01/07 Javascript
js+html5实现的自由落体运动效果代码
2016/01/28 Javascript
bootstrap flask登录页面编写实例
2016/11/01 Javascript
javascript中的后退和刷新实现方法
2016/11/10 Javascript
js数组操作方法总结(必看篇)
2016/11/22 Javascript
解决nodejs中使用http请求返回值为html时乱码的问题
2017/02/18 NodeJs
JS中实现函数return多个返回值的实例
2017/02/21 Javascript
关于ligerui子页面关闭后,父页面刷新,重新加载的方法
2019/09/27 Javascript
JQuery表单元素取值赋值方法总结
2020/05/12 jQuery
Python判断变量是否已经定义的方法
2014/08/18 Python
Python Queue模块详解
2014/11/30 Python
Python多线程编程简单介绍
2015/04/13 Python
pygame学习笔记(5):游戏精灵
2015/04/15 Python
实时获取Python的print输出流方法
2019/01/07 Python
python 将大文件切分为多个小文件的实例
2019/01/14 Python
Python利用sqlacodegen自动生成ORM实体类示例
2019/06/04 Python
pandas 使用均值填充缺失值列的小技巧分享
2019/07/04 Python
python多线程与多进程及其区别详解
2019/08/08 Python
python使用requests.session模拟登录
2019/08/09 Python
python selenium自动化测试框架搭建的方法步骤
2020/06/14 Python
canvas实现手机的手势解锁的步骤详细
2020/03/16 HTML / CSS
介绍一下Linux文件的记录形式
2012/04/18 面试题
2015年老干部工作总结
2015/04/23 职场文书
社区禁毒宣传活动总结
2015/05/07 职场文书
详解JavaScript中Arguments对象用途
2021/08/30 Javascript
python套接字socket通信
2022/04/01 Python