python opencv将图片转为灰度图的方法示例

作者:修炼之路 时间:2021-03-24 22:22:54 

使用opencv将图片转为灰度图主要有两种方法,第一种是将彩 * 转为灰度图,第二种是在使用OpenCV读取图片的时候直接读取为灰度图

将彩 * 转为灰度图


import cv2
import numpy as np

if __name__ == "__main__":
 img_path = "timg.jpg"
 img = cv2.imread(img_path)
 #获取图片的宽和高
 width,height = img.shape[:2][::-1]
 #将图片缩小便于显示观看
 img_resize = cv2.resize(img,
 (int(width*0.5),int(height*0.5)),interpolation=cv2.INTER_CUBIC)
 cv2.imshow("img",img_resize)
 print("img_reisze shape:{}".format(np.shape(img_resize)))

#将图片转为灰度图
 img_gray = cv2.cvtColor(img_resize,cv2.COLOR_RGB2GRAY)
 cv2.imshow("img_gray",img_gray)
 print("img_gray shape:{}".format(np.shape(img_gray)))
 cv2.waitKey()

img_reisze shape:(337, 600, 3)
img_gray shape:(337, 600)

使用opencv读取图片的时候,默认使用的是BGR来读取图片的,可以看到原始读取的图片是3通道的,经过转换之后变成了单通道。

python opencv将图片转为灰度图的方法示例

直接将图片采用灰度图的方式进行读取


import cv2
import numpy as np

if __name__ == "__main__":
 img_path = "timg.jpg"
 img = cv2.imread(img_path)
 #获取图片的宽和高
 width,height = img.shape[:2][::-1]
 #将图片缩小便于显示观看
 img_resize = cv2.resize(img,
 (int(width*0.5),int(height*0.5)),interpolation=cv2.INTER_CUBIC)
 cv2.imshow("img",img_resize)
 print("img_reisze shape:{}".format(np.shape(img_resize)))

#读取灰度图
 img_gray = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE)
 #将图片缩小便于显示观看
 img_gray = cv2.resize(img_gray,
 (int(width*0.5),int(height*0.5)),interpolation=cv2.INTER_CUBIC)
 cv2.imshow("img_gray",img_gray)
 print("img_gray shape:{}".format(np.shape(img_gray)))
 cv2.waitKey()

img_reisze shape:(337, 600, 3)
img_gray shape:(337, 600)

python opencv将图片转为灰度图的方法示例

来源:https://blog.csdn.net/sinat_29957455/article/details/84845016

标签:python,opencv,灰度图
0
投稿

猜你喜欢

  • Dlib+OpenCV深度学习人脸识别的方法示例

    2022-11-08 06:34:42
  • 优雅管理Go Project生命周期

    2023-06-16 01:10:42
  • python实现kNN算法

    2023-01-24 13:58:06
  • 基于Django用户认证系统详解

    2023-04-13 15:35:13
  • windowns使用PySpark环境配置和基本操作

    2021-04-12 06:43:06
  • 详解MySQL 数据库优化方法

    2010-08-12 14:50:00
  • 剖析网页设计中的几何圆

    2010-10-19 12:27:00
  • PHP html_entity_decode()函数讲解

    2023-06-01 00:59:43
  • 用一个例子来认识innerText,innerHTML

    2007-12-24 17:17:00
  • 关于Python中 循环器 itertools的介绍

    2023-11-23 02:48:21
  • 按钮在 IE 中两边被拉伸的 BUG

    2008-11-17 20:37:00
  • Oracle 添加用户并赋权,修改密码,解锁,删除用户的方法

    2009-10-14 11:37:00
  • SQL的Join使用图解教程

    2012-08-21 10:47:23
  • 如何从SQL数据库中调用图片?

    2009-11-15 19:59:00
  • 浅谈pytorch、cuda、python的版本对齐问题

    2022-12-03 13:04:54
  • jquery的$(document).ready()和onload的加载顺序

    2023-08-23 18:57:40
  • javascript与jsp发送请求到servlet的几种方式实例

    2023-06-15 15:59:30
  • Python实现提取给定网页内的所有链接

    2022-03-29 19:01:11
  • python如何给内存和cpu使用量设置限制

    2021-03-04 00:43:00
  • python调用并链接MATLAB脚本详解

    2021-12-11 07:16:42
  • asp之家 网络编程 m.aspxhome.com