Method for modifying picture pixel value of Python
- 2021-07-09 08:51:21
- OfStack
When doing the semantic segmentation project, the annotated picture is not standard, and the type is RGBA, and it is the category represented by part of A, so it is necessary to convert the picture into RGB picture
# -*- coding:utf8 -*-
import os
from PIL import Image
im = Image.open('123.png')# Open picture
pix = im.load()# Import Pixel
width = im.size[0]# Get Width
height = im.size[1]# Get length
for x in range(width):
for y in range(height):
r,g,b,a = im.getpixel((x,y))
rgba=(r,g,b,a)
if(a==0):
im.putpixel((x,y),(0,0,0,0))
if(a==255):
im.putpixel((x,y),(255,255,255,255))
im = im.convert('RGB')
im.save('456.png')
Batch processing method
# -*- coding:utf8 -*-
import os
from PIL import Image
path = 'SegmentationClass(RGBA)/'
savedpath = 'SegmentationClass/'
filelist = os.listdir(path)
for item in filelist:
im = Image.open( path + item )# Open picture
width = im.size[0]# Get Width
height = im.size[1]# Get length
for x in range(width):
for y in range(height):
r,g,b,a = im.getpixel((x,y))
if(a==0):
im.putpixel((x,y),(0,0,0,0))
if(a==255):
im.putpixel((x,y),(255,255,255,255))
im = im.convert('RGB')
im.save(savedpath + item)
print('item of %s is saved '%(item))