0
点赞
收藏
分享

微信扫一扫

如何将通过Image.open读出的图片从单通道->三通道


如何将通过Image.open读出的图片从单通道->三通道

以下代码是来自python-单通道图像转三通道_单通道图像扩展为三通道_哗啦呼啦嘿的博客

import os
import cv2
import numpy as np
import PIL.Image as Image
import os

img_path='/home/gyx/QR/qr_detect_model/dataset/images_all_channel_1/'
save_img_path='/home/gyx/QR/qr_detect_model/dataset/images_all_channel_3/'
for img_name in os.listdir(img_path):
    image=Image.open(img_path+img_name)
    if len(image.split())==1: #查看通道数
        print(len(image.split()))
        print(img_path+img_name)
        img = cv2.imread(img_path+img_name)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img2 = np.zeros_like(img)
        img2[:,:,0] = gray
        img2[:,:,1] = gray
        img2[:,:,2] = gray
        cv2.imwrite(save_img_path+img_name, img2)
        image=Image.open(save_img_path+img_name)
        print(len(image.split()))
    else:
        image.save(save_img_path+img_name)

其实可以采用以下方式进行数据读取,可以减少代码量,更加方便。若图像是单通道图像,则调用convert方法将其转换为三通道图像。最后可以通过show方法显示图像。

PIL.Image.open('normal_test.jpeg').convert('RGB')

代码改进,如下所示:

import os
import cv2
import numpy as np
import PIL.Image as Image
import os
img_path='/home/gyx/QR/qr_detect_model/dataset/images_all_channel_1/'
save_img_path='/home/gyx/QR/qr_detect_model/dataset/images_all_channel_3/'
for img_name in os.listdir(img_path):
    image=Image.open(img_path+img_name)
    if len(image.split())==1: #查看通道数
        image= Image.open(img_path+img_name).convert('RGB')
        image.save(save_img_path+img_name)
    else:
        image.save(save_img_path+img_name)


举报

相关推荐

0 条评论