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后台管理程序
Apr 13 Python
如何高效使用Python字典的方法详解
Aug 31 Python
使用sklearn之LabelEncoder将Label标准化的方法
Jul 11 Python
使用python动态生成波形曲线的实现
Dec 04 Python
Python concurrent.futures模块使用实例
Dec 24 Python
浅谈python的elementtree模块处理中文注意事项
Mar 06 Python
python实现人像动漫化的示例代码
May 17 Python
Python xml、字典、json、类四种数据类型如何实现互相转换
May 27 Python
Python __slots__的使用方法
Nov 15 Python
python使用numpy中的size()函数实例用法详解
Jan 29 Python
用Python远程登陆服务器的步骤
Apr 16 Python
Python实现双向链表基本操作
May 25 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
天使彦史上最神还原,性别曝光的那一刻,百万网友恋爱了
2020/03/02 国漫
php unset全局变量运用问题的深入解析
2013/06/17 PHP
PHP发送短信代码分享
2015/08/11 PHP
PHP常用函数总结(180多个)
2016/12/25 PHP
PDO::prepare讲解
2019/01/29 PHP
JS保留两位小数,多位小数的示例代码
2014/01/07 Javascript
javascript实现动态加载CSS
2015/01/26 Javascript
jQuery仿Flash上下翻动的中英文导航菜单实例
2015/03/10 Javascript
分享经典的JavaScript开发技巧
2015/11/21 Javascript
jQuery内容折叠效果插件用法实例分析(附demo源码)
2016/04/28 Javascript
谈谈JavaScript数组常用方法总结
2017/01/24 Javascript
node.js中debug模块的简单介绍与使用
2017/04/25 Javascript
vue之数据交互实例代码
2017/06/16 Javascript
JavaScript实现HTML5游戏断线自动重连的方法
2017/09/18 Javascript
Three.js中网格对象MESH的属性与方法详解
2017/09/27 Javascript
对Vue2 自定义全局指令Vue.directive和指令的生命周期介绍
2018/08/30 Javascript
Vue移动端项目实现使用手机预览调试操作
2020/07/18 Javascript
python中函数总结之装饰器闭包详解
2016/06/12 Python
python xlsxwriter库生成图表的应用示例
2018/03/16 Python
简单实现python聊天程序
2018/04/01 Python
TensorFlow Session使用的两种方法小结
2018/07/30 Python
Python实现的ftp服务器功能详解【附源码下载】
2019/06/26 Python
python mysql断开重连的实现方法
2019/07/26 Python
Python Django Cookie 简单用法解析
2019/08/13 Python
Python 字节流,字符串,十六进制相互转换实例(binascii,bytes)
2020/05/11 Python
CSS3网格的三个新特性详解
2014/04/04 HTML / CSS
美国著名首饰网站:BaubleBar
2016/08/29 全球购物
Baracuta官方网站:Harrington夹克,G9,G4,G10等
2018/03/06 全球购物
Guess欧洲官网:美国服饰品牌
2019/08/06 全球购物
使用索引有什么好处
2016/07/27 面试题
大二学生学习个人自我评价
2014/01/19 职场文书
外贸采购员岗位职责
2014/03/08 职场文书
招股说明书范本
2014/05/06 职场文书
党员群众路线承诺书
2014/05/20 职场文书
台风停课通知
2015/04/24 职场文书
2016入党积极分子党校培训心得体会
2016/01/06 职场文书