欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-03-18 09:46:15|栏目:Python代码|点击:

使用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通道的,经过转换之后变成了单通道。

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

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 if 判断选择结构的实例详解

栏    目:Python代码

下一篇:简单了解Django项目应用创建过程

本文标题:python opencv将图片转为灰度图的方法示例

本文地址:http://www.codeinn.net/misctech/83240.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有