问题
on Pyhton I wanted to create a picture that goes from black to white, and I wrote the following code. But I think I'm doing a very small mistake, and that's the result.
I actually wanted to create a similar image. Can you see where I made a mistake?
import numpy as np
from PIL import Image
width = 100
height = 100
img = np.zeros((height, width), dtype=np.uint8)
xx, yy=np.mgrid[:height, :width]
circle = (xx - 50)**2 + (yy- 50)**2
for x in range (img.shape[0]):
for y in range (img.shape[1]):
intensity = circle[x][y]
img[x][y]= intensity
Image.fromarray(img, 'L').show()
Image.fromarray(img, 'L').save ('circlebad.png', 'PNG')
<----------------------------------Edit---------------------------------------->
When I insert; intensity = intensity / 512
my problem solved. Last codes;
import numpy as np
from PIL import Image
width = 100
height = 100
img = np.zeros((height, width), dtype=np.uint8)
xx, yy=np.mgrid[:height, :width]
circle = (xx - 50)**2 + (yy- 50)**2
for x in range (img.shape[0]):
for y in range (img.shape[1]):
intensity = circle[x][y]
intensity = intensity / 512
img[x][y]= intensity
Image.fromarray(img, 'L').show()
Image.fromarray(img, 'L').save ('circlebad.png', 'PNG')
回答1:
As others have noted, the reason you are getting the output in the top image is because the intensities need to be in range(256)
, and Numpy arithmetic is effectively doing % 256
on the values your code is producing.
Here's a repaired version of your code.
import numpy as np
from PIL import Image
width = height = 320
radius = (width - 1) / 2
xx, yy = np.mgrid[:height, :width]
# Compute the raw values
circle = (xx - radius) ** 2 + (yy - radius) ** 2
#Brightness control
maxval = 255
valscale = maxval / (2 * radius ** 2)
circle = (circle * valscale).astype(np.uint8)
img = Image.fromarray(circle, 'L')
img.show()
img.save('circle.png')
output: circle.png
来源:https://stackoverflow.com/questions/46512983/python-blurred-image-creation-to-create-a-beautifully-colored-painting-from-bla