Skip to content

Instantly share code, notes, and snippets.

@cckwes
Created May 24, 2015 01:18
Show Gist options
  • Save cckwes/84a71d175850f34f7890 to your computer and use it in GitHub Desktop.
Save cckwes/84a71d175850f34f7890 to your computer and use it in GitHub Desktop.
Create dot pattern image using Python3 and PIL
from PIL import Image, ImageDraw
img = Image.open("beach.jpg")
pixels = img.load()
# Choose the pixelization length
pixelization_length = 6
# Define the pixelize and mask image
pixelize_image = Image.new('RGBA', img.size)
mask_image = Image.new('RGBA', img.size, 'black')
x_units = int(img.size[0] / pixelization_length)
y_units = int(img.size[1] / pixelization_length)
draw = ImageDraw.Draw(pixelize_image)
mask_draw = ImageDraw.Draw(mask_image)
for i in range(0, x_units):
for j in range(0, y_units):
mask_draw.ellipse((i * pixelization_length, j * pixelization_length,
i * pixelization_length + pixelization_length - 1,
j * pixelization_length + pixelization_length - 1),
(255,255,255,0))
total_red_intensity = total_green_intensity = total_blue_intensity = 0
averaging_pixel_number = pixelization_length * pixelization_length
for k in range(0, pixelization_length):
for l in range(0, pixelization_length):
total_red_intensity += pixels[i * pixelization_length + k, j * pixelization_length + l][0]
total_green_intensity += pixels[i * pixelization_length + k, j * pixelization_length + l][1]
total_blue_intensity += pixels[i * pixelization_length + k, j * pixelization_length + l][2]
average_red_intensity = int(total_red_intensity / averaging_pixel_number)
average_green_intensity = int(total_green_intensity / averaging_pixel_number)
average_blue_intensity = int(total_blue_intensity / averaging_pixel_number)
draw.rectangle((i * pixelization_length, j * pixelization_length,
i * pixelization_length + pixelization_length - 1,
j * pixelization_length + pixelization_length - 1),
(average_red_intensity, average_green_intensity, average_blue_intensity))
# Save the intermediate images for demo purpose
mask_image.save("mask.png")
pixelize_image.save("pixelize_beach.jpg")
pixelize_image.paste(mask_image, mask=mask_image)
pixelize_image.save("result.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment