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调用cmd命令行制作刷博器
Jan 13 Python
python批量修改文件名的实现代码
Sep 01 Python
在Python的web框架中中编写日志列表的教程
Apr 30 Python
Python类属性的延迟计算
Oct 22 Python
如何在python中使用selenium的示例
Dec 26 Python
python如何读写json数据
Mar 21 Python
Python编写一个优美的下载器
Apr 15 Python
Flask框架 CSRF 保护实现方法详解
Oct 30 Python
wxPython实现整点报时
Nov 18 Python
Python虚拟环境的创建和使用详解
Sep 07 Python
详解python os.path.exists判断文件或文件夹是否存在
Nov 16 Python
浅析python中特殊文件和特殊函数
Feb 24 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
兼容IE和FF的图片上传前预览js代码
2013/05/28 Javascript
深入分析原生JavaScript事件
2014/12/29 Javascript
JavaScript中捕获/阻止捕获、冒泡/阻止冒泡方法
2016/12/07 Javascript
javascript中递归的两种写法
2017/01/17 Javascript
Vuex之理解state的用法实例
2017/04/19 Javascript
Bootstrap响应式导航由768px变成992px的实现代码
2017/06/15 Javascript
javascript按顺序加载运行js方法
2017/12/01 Javascript
vue给组件传递不同的值方法
2018/09/29 Javascript
解决layui数据表格排序图标被超出的表头挤出去的问题
2019/09/19 Javascript
如何基于JavaScript判断图片是否加载完成
2019/12/28 Javascript
jquery选择器和属性对象的操作实例分析
2020/01/10 jQuery
ES6学习笔记之let与const用法实例分析
2020/01/22 Javascript
Python中针对函数处理的特殊方法
2014/03/06 Python
Python简单实现安全开关文件的两种方式
2016/09/19 Python
Python基于动态规划算法解决01背包问题实例
2017/12/06 Python
使用Python机器学习降低静态日志噪声
2018/09/29 Python
Python 运行 shell 获取输出结果的实例
2019/01/07 Python
Python3.5基础之NumPy模块的使用图文与实例详解
2019/04/24 Python
Django学习笔记之为Model添加Action
2019/04/30 Python
python实现LRU热点缓存及原理
2019/10/29 Python
Python3爬虫中Ajax的用法
2020/07/10 Python
Ubuntu20下的Django安装的方法步骤
2021/01/24 Python
介绍一下Linux中的链接
2016/05/28 面试题
J2EE系统只能是基于web
2015/09/08 面试题
建筑专业毕业生推荐信
2013/11/21 职场文书
应聘医药销售自荐书范文
2014/02/08 职场文书
《雨霖铃》听课反思
2014/02/13 职场文书
工商治理实习生的自我评价分享
2014/02/20 职场文书
《太阳》教学反思
2014/02/21 职场文书
家长会标语
2014/06/24 职场文书
4s店销售经理岗位职责
2014/07/19 职场文书
七年级上册语文教学计划
2015/01/22 职场文书
会议邀请函
2015/01/30 职场文书
隐形的翅膀观后感
2015/06/10 职场文书
一年级下册数学教学反思
2016/02/16 职场文书
postgresql中如何执行sql文件
2023/05/08 PostgreSQL