pytorch使用(二)python读取图片各点灰度值or怎么读、转换灰度图

发布时间 2023-07-16 11:20:26作者: DuJunlong

python读取图片各点灰度值

方法一:在使用OpenCV读取图片的同时将图片转换为灰度图:

img = cv2.imread(imgfile, cv2.IMREAD_GRAYSCALE)
print("cv2.imread(imgfile, cv2.IMREAD_GRAYSCALE)结果如下:")
print('大小:{}'.format(img.shape))
print("类型:%s"%type(img))
print(img)  

方法二:使用OpenCV,先读取图片,然后在转换为灰度图:

img = cv2.imread(imgfile)
#print(img.shape)
#print(img)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Y = 0.299R + 0.587G + 0.114B
print("cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)结果如下:")
print('大小:{}'.format(gray_img.shape))
print("类型:%s" % type(gray_img))
print(gray_img)

 

方法三:使用PIL库中的Image模块:

img = np.array(Image.open(imgfile).convert('L'), 'f') #读取图片,灰度化,转换为数组,L = 0.299R + 0.587G + 0.114B。'f'为float类型
print("Image方法的结果如下:")
print('大小:{}'.format(img.shape))
print("类型:%s" % type(img))
print(img)  

方法四:TensorFlow方法:

with tf.Session() as sess:
img = tf.read_file(imgfile) #读取图片,
img_data = tf.image.decode_jpeg(img, channels=3) #解码
#img_data = sess.run(tf.image.decode_jpeg(img, channels=3))
img_data = sess.run(tf.image.rgb_to_grayscale(img_data)) #灰度化
print('大小:{}'.format(img_data.shape))
print("类型:%s" % type(img_data))
print(img_data)  

https://juejin.cn/s/python%E8%AF%BB%E5%8F%96%E5%9B%BE%E7%89%87%E5%90%84%E7%82%B9%E7%81%B0%E5%BA%A6%E5%80%BC