python3读取图片并灰度化图片的四种方法

方法一:在使用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)

你可能感兴趣的:(深度学习,opencv,计算机视觉,python)