首页 > 解决方案 > 如何使用python创建具有每个点的RGB值的NumPy图像数组?

问题描述

我正在尝试将图像分成两部分并将这两个图像合并回来。我尝试使用 NumPy 从图像上的每个点减去一个随机值并存储该值以使其成为新图像。然后我收到“照片无法打开此文件,因为当前不支持格式化,或者文件已损坏。” 在第二张图片上。那么如何创建具有这些值的图像呢?

import numpy
import random
from PIL import Image
a = Image.new('RGB', [1280, 720], (255, 255, 255))
a = numpy.array(a)
value = []
for x in a:
    for y in range(0, len(x)):
        temp = [random.randrange(0, 255), random.randrange(
            0, 255), random.randrange(0, 255)]
        b = numpy.array(temp)
        x[y] = x[y]-b
        value.append(temp)
a = Image.fromarray(a)
a.show()
#print(value)
#print(len(value))  # 1280*720=921600
c = numpy.array(value)
d = Image.fromarray(c)
d.show()

标签: python-3.xnumpypython-imaging-library

解决方案


我想到了。我试图创建一个相同大小的新白色图像并循环通过它来添加值。

import numpy
import random
from PIL import Image
a = Image.open('test.jpg')
a = numpy.array(a)
value = []
for x in a:
    for y in range(0, len(x)):
        temp = [random.randrange(0,255),random.randrange(0,255),random.randrange(0,255)]
        b = numpy.array(temp)
        x[y] = x[y]-b
        value.append(temp)
a = Image.fromarray(a)
b=Image.new('RGB',a.size,(255,255,255))
b=numpy.array(b)
counter=0
for x in b:
    for y in range(0,len(x)):
        x[y]=tuple(value[counter])
        counter+=1
b=Image.fromarray(b)
a=numpy.array(a)
b=numpy.array(b)
a=numpy.add(a,b)
a=Image.fromarray(a)
a.show()

推荐阅读