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

yipeiwu_com5年前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设计】。

相关文章

python制作简单五子棋游戏

本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 #五子棋 ‘'' 矩阵做棋盘 16*16 “+” 打印棋盘 for for 游戏是否结束 开始下棋 wh...

Atom Python 配置Python3 解释器的方法

环境 Mac Python3.6.4 Atom 背景 Atom 执行Python Code 使用Script Package,执行快捷键cmd + i。 但是默认是执行Mac 系统的2....

Selenium鼠标与键盘事件常用操作方法示例

Selenium鼠标与键盘事件常用操作方法示例

本文实例讲述了Selenium鼠标与键盘事件常用操作方法。分享给大家供大家参考,具体如下: Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就...

对python 操作solr索引数据的实例详解

对python 操作solr索引数据的实例详解

测试代码1: def test(self): data = {"add": {"doc": {"id": "100001", "*字段名*": u"我是一个大好人"}}} p...

Python中那些 Pythonic的写法详解

前言 Martin(Bob大叔)曾在《代码整洁之道》一书打趣地说:当你的代码在做 Code Review 时,审查者要是愤怒地吼道: “What the fuck is this shi...