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

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

相关文章

python3学习笔记之多进程分布式小例子

python3学习笔记之多进程分布式小例子

最近一直跟着廖大在学Python,关于分布式进程的小例子挺有趣的,这里做个记录。 分布式进程 Python的multiprocessing模块不但支持多进程,其中managers子模块还...

Python的lambda匿名函数的简单介绍

lambda函数也叫匿名函数,即,函数没有具体的名称。先来看一个最简单例子:复制代码 代码如下:def f(x):return x**2print f(4)Python中使用lambda...

python os.listdir按文件存取时间顺序列出目录的实例

如下所示: import os DIR = "/home/serho/workspace/lisp" def compare(x, y): stat_x = os.stat(D...

python利用lxml读写xml格式的文件

之前在转换数据集格式的时候需要将json转换到xml文件,用lxml包进行操作非常方便。 1. 写xml文件 a) 用etree和objectify from lxml import...

利用pyshp包给shapefile文件添加字段的实例

在已有的shapefile文件的基础上增加字段: # -*- coding:gb2312 -*- import shapefile r=shapefile.Reader(r"C:...