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

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

eb33ee2953f0a7f7951ffbfa0fb94bf4.png

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

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)

f044b1a229b6d4837e06ffb20a88ad73.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2019-07-29

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值