Use the Image module of the Python-PIL library to restore the RGB matrix to a picture
Recently, I encountered a big problem when using Python to simulate the k-means algorithm. How to restore the RGB matrix after clustering to a picture?
Let's use a small example to record the implementation process.
step
1. Open the image and get its corresponding RGB matrix
#读取图像
from PIL import Image
def getImgData():
img = Image.open('example.jpg','r')
print(img.size)
lst = list(img.getdata())
return lst
img.size is (500,358)
2. Convert the RGB matrix to a list of n*m; n refers to the number of rows in the picture (500), and m refers to the number of columns in the picture (358)
lst = getImgData()
lst1 = []
for i in range(0,500):
lst1.append(lst[357*i:357*i+357])
3. Verify if the conversion is successful
for val,i in zip(lst1,range(0,len(lst1))):
print(val)
print(len(val))
4. Convert each RGB to pixels, and then save as a new picture
newimg = Image.new('RGB',(500,358))
i=0
for val,i in zip(lst1,range(0,len(lst1))):
for j in range(0,len(val)):
newimg.putpixel((i,j),(int(val[j][0]),int(val[j][1]),int(val[j][2])))
newimg.save('flag.jpg')
Complete code
#读取图像
from PIL import Image
def getImgData():
img = Image.open('example.jpg','r')
print(img.size)
lst = list(img.getdata())
return lst
lst = getImgData()
lst1 = []
for i in range(0,500):
lst1.append(lst[357*i:357*i+357])
for val,i in zip(lst1,range(0,len(lst1))):
print(val)
print(len(val))
print(i)
newimg = Image.new('RGB',(500,358))
i=0
for val,i in zip(lst1,range(0,len(lst1))):
for j in range(0,len(val)):
newimg.putpixel((i,j),(int(val[j][0]),int(val[j][1]),int(val[j][2])))
newimg.save('flag.jpg')
operation result
I am a Python rookie, please criticize and correct me in time.