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实现端口转发器的方法
Mar 13 Python
Python编程实现粒子群算法(PSO)详解
Nov 13 Python
python实现简易云音乐播放器
Jan 04 Python
Python中%是什么意思?python中百分号如何使用?
Mar 20 Python
python的格式化输出(format,%)实例详解
Jun 01 Python
Python3用tkinter和PIL实现看图工具
Jun 21 Python
详解Python数据分析--Pandas知识点
Mar 23 Python
python实现控制电脑鼠标和键盘,登录QQ的方法示例
Jul 06 Python
python调用Matplotlib绘制分布点图
Oct 18 Python
pandas-resample按时间聚合实例
Dec 27 Python
Python numpy多维数组实现原理详解
Mar 10 Python
python tkinter的消息框模块(messagebox,simpledialog)
Nov 07 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原理之Session Gc的一个小概率Notice
2011/04/12 PHP
PHP删除指定目录中的所有目录及文件的方法
2015/02/26 PHP
Yii中创建自己的Widget实例
2016/01/05 PHP
PHP中多线程的两个实现方法
2016/10/14 PHP
php 浮点数比较方法详解
2017/05/05 PHP
(currentStyle)javascript为何有时用style得不到已设定的CSS的属性
2007/08/15 Javascript
用AJAX返回HTML片段中的JavaScript脚本
2010/01/04 Javascript
Jquery Ajax学习实例 向页面发出请求,返回XML格式数据
2010/03/14 Javascript
JQuery 获取json数据$.getJSON方法的实例代码
2013/08/02 Javascript
兼容所有浏览器的js复制插件Zero使用介绍
2014/03/19 Javascript
js换图片效果可进行定时操作
2014/06/09 Javascript
js实现ArrayList功能附实例代码
2014/10/29 Javascript
非jQuery实现照片散落桌子上,单击放大的LightBox效果
2014/11/28 Javascript
全面解析Bootstrap中nav、collapse的使用方法
2016/05/22 Javascript
BootStrap的Datepicker控件使用心得分享
2016/05/25 Javascript
Javascript中浏览器窗口的基本操作总结
2016/08/18 Javascript
你不知道的 javascript【推荐】
2017/01/08 Javascript
react.js 翻页插件实例代码
2017/01/19 Javascript
利用node.js实现自动生成前端项目组件的方法详解
2017/07/12 Javascript
VueJs单页应用实现微信网页授权及微信分享功能示例
2017/07/26 Javascript
在原生不支持的旧环境中添加兼容的Object.keys实现方法
2017/09/11 Javascript
使用Bootstrap + Vue.js实现表格的动态展示、新增和删除功能
2017/11/27 Javascript
vue中$refs的用法及作用详解
2018/04/24 Javascript
JavaScript静态作用域和动态作用域实例详解
2019/06/17 Javascript
JS数组方法push()、pop()用法实例分析
2020/01/18 Javascript
JS call()及apply()方法使用实例汇总
2020/07/11 Javascript
Python中urllib2模块的8个使用细节分享
2015/01/01 Python
对pytorch网络层结构的数组化详解
2018/12/08 Python
python判断字符串以什么结尾的实例方法
2020/09/18 Python
自我评价个人范文
2013/12/16 职场文书
工厂门卫的岗位职责
2014/07/27 职场文书
普通话演讲稿
2014/09/03 职场文书
市贸粮局召开党的群众路线教育实践活动总结大会新闻稿
2014/10/21 职场文书
酒店工程部岗位职责
2015/02/12 职场文书
初三毕业感言
2015/07/31 职场文书
Python实现聚类K-means算法详解
2022/07/15 Python