这篇文章主要介绍了python opencv将图片转为灰度图的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
![8878c2bd174aa54dc8694d0b1bd6163d.png](https://i-blog.csdnimg.cn/blog_migrate/1d6a61fde209938df42c0bd7c190ad89.jpeg)
使用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_r