【发布时间】:2020-03-28 11:18:36
【问题描述】:
我正在尝试在 Python 3 中创建一个用于 Web 应用程序的图像系统。这个想法是从磁盘加载图像并为其添加一些随机噪声。当我尝试这个时,我得到一个看起来完全随机的图像,与原始图像不同:
import cv2
import numpy as np
from skimage.util import random_noise
from random import randint
from pathlib import Path
from PIL import Image
import io
image_files = [
{
'name': 'test1',
'file': 'test1.png'
},
{
'name': 'test2',
'file': 'test2.png'
}
]
def gen_image():
rand_image = randint(0, len(image_files)-1)
image_file = image_files[rand_image]['file']
image_name = image_files[rand_image]['name']
image_path = str(Path().absolute())+'/img/'+image_file
img = cv2.imread(image_path)
noise_img = random_noise(img, mode='s&p', amount=0.1)
img = Image.fromarray(noise_img, 'RGB')
fp = io.BytesIO()
img.save(fp, format="PNG")
content = fp.getvalue()
return content
gen_image()
我也尝试过使用 pypng:
import png
# Added the following to gen_image()
content = png.from_array(noise_img, mode='L;1')
content.save('image.png')
如何从磁盘加载 png(具有 alpha 透明度),为其添加一些噪点,然后将其返回,以便它可以通过 Web 服务器代码(flask、aiohttp 等)显示。
正如 makayla 的回答中所指出的,这使它变得更好:noise_img = (noise_img*255).astype(np.uint8) 但颜色仍然错误并且没有透明度。
这是更新后的函数:
def gen_image():
rand_image = randint(0, len(image_files)-1)
image_file = image_files[rand_image]['file']
image_name = image_files[rand_image]['name']
image_path = str(Path().absolute())+'/img/'+image_file
img = cv2.imread(image_path)
cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Problem exists somewhere below this line.
img = random_noise(img, mode='s&p', amount=0.1)
img = (img*255).astype(np.uint8)
img = Image.fromarray(img, 'RGB')
fp = io.BytesIO()
img.save(fp, format="png")
content = fp.getvalue()
return content
这将弹出一个预噪声图像并返回噪声图像。返回的图像中存在 RGB(和 alpha)问题。
我认为问题在于它必须是RGBA,但是当我更改为ValueError: buffer is not large enough时,我得到了ValueError: buffer is not large enough
【问题讨论】:
-
我没有看到任何试图在原始图像中添加噪点的东西。
-
noise_img = random_noise(img, mode='s&p', amount=0.1) -
更新了问题的功能和评论。
-
需要 RGBA 但形状不对
标签: python python-3.x image-processing signal-processing