python3 An example of converting pictures into RGB pictures with PIL

  • 2021-07-09 08:48:54
  • OfStack

Feelings

When we do deep learning to process pictures, If it is a data set made or collected by ourselves, it is inevitable to process the data set, and then most models only support pictures in RGB format. At this time, we need to convert pictures in other formats, such as gray-scale images into RGB pictures, and there is only a tutorial on converting gray-scale images into RGB on the Internet. I will make up for one vacancy here.


from PIL import Image
import numpy as np
L_path='train/5509031.jpg'
L_image=Image.open(L_path)
out = L_image.convert("RGB")
img=np.array(out)
print(out.mode)
print(out.size)
print(img.shape)

Then you can switch.

If it is a large number of pictures, then it is stupid to judge by cycle:


from PIL import Image
from tqdm import tqdm
import numpy as np
root_path='data'
for item in tqdm(examples):
 arr=item.strip().split('*')
 img_name=arr[0]
 image_path=os.path.join(root_path,img_name)
 img=Image.open(image_path)
 if(img.mode!='RGB'):
  img = img.convert("RGB")
  img=np.array(img)
  print(img_name)
  print(img.shape)
 # add your code

My image path is read through an txt file. Here are some examples of train. txt:


train/1769512.jpg* postcard construction 67 mixed media epoxy collage 7 x 135 x 4* art||drawing||sculpture
train/5020991.jpg* en el cuadro de honor de todas las 50appsalud en un grfico en espaol* mhealth
train/3525659.jpg* information mogadishu port expansion turkish company* somalia


Related articles: