Pixel art as well as various sets for hand crafting

Overview

Рефакторинг

В последнее время очень популярен пиксельарт, а также разнообразные наборы для ручного крафта.

Один из проектов, mozabrick, например, предлагает что-то типа мозайки из квадратиков 5 градаций серого, из которой можно собрать любую фотографию.

Преобразование

С помощью приложения вы накладываете фильтр, получаете черно-белый пиксель-арт, который можно набрать уже мозаикой.

Иногда делают такие панно прямо на зданиях.

Здание

Вот я прогнал через фильтр свое фото:

Фото с фильтром

Вот так примерно выглядит процесс сборки панно:

Сборка

Естественно, появилось желание написать вручную такой фильтр. Он может понадобится для пиксель-арта, создания игр с анимацией а-ля ранний Mortal Kombat, японских кроссвордов или для вязки свитеров ближе к НГ. Для чтения-записи изображений используется библиотека pillow, для всех остальных манипуляций — numpy.

from PIL import Image
import numpy as np
img = Image.open("img2.jpg")
arr = np.array(img)
a = len(arr)
a1 = len(arr[1])
i = 0
while i < a - 11:
    j = 0
    while j < a1 - 11:
        s = 0
        for n in range(i, i + 10):
            for n1 in range(j, j + 10):
                n1 = arr[n][n1][0]
                n2 = arr[n][n1][1]
                n3 = arr[n][n1][2]
                M = n1 + n2 + n3
                s += M
        s = int(s // 100)
        for n in range(i, i + 10):
            for n1 in range(j, j + 10):
                arr[n][n1][0] = int(s // 50) * 50
                arr[n][n1][1] = int(s // 50) * 50
                arr[n][n1][2] = int(s // 50) * 50
        j = j + 10
    i = i + 10
res = Image.fromarray(arr)
res.save('res.jpg')

Картинка прелставляет сосбой трехмерный массив, где два измерения — таблица с пикселями, а пиксель — что-то то типа массива [12, 240, 123], содержащего компоненты RGB.

Я ввел размер элемента мозайки 10x10 пикселей. Среди 100 пикселей из большой ячейки я просто выясняю среднюю яркость и закрашиваю их все в один цвет средней яркости, приведенный к ступеньке с шагом 50.

В результате из такой картинки:

Исходная каритинка

Получается такая:

Результат

Это не тот результат, на который я рассчитывал, и вам предстоит много поработать с моим кодом.

Представьте этапы как отдельные коммиты.

Что делать?

1 этап

К коду настолько много вопросов, что я даже не знаю с чего начать...

  • В коде содержатся как минимум четыре ошибки, которые заставляют фильтр работать не так, как нужно.
    • Одна из них очень нетипична для программиста на Питоне и связана с переполнением беззнакового целого numpy.uint8.
    • В одном месте я запутался с именами переменных.
    • Неверно считаю компоненты серого цвета (забываю поделить на 3).
    • Неверно работаю с граничными условиями, в результате чего справа и внизу остались необработанные полосы по 10 пикселей.

2 этап

  • PEP8.
  • Именование переменных.
  • Возможность управлять размерами мозайки (сейчас — только 10x10).
  • Возможность управлять градациями серого (сейчас — с шагом 50). Лучше сделать просто в виде задания количества шагов. Например: 4 градации, 6 градаций.
  • Выделение функций.

3 этап

  • По возможности убрать ручные циклы, заменив их матричными преобразованиями.

4 этап

  • Возможно, переписать в консольную утилиту, которой на вход подаются имена исходного изображения и результата. Сейчас чтобы заставить код работать с другой картинкой, его надо исправлять.
An executor that wraps 3D mesh models and encodes 3D content documents to d-dimension vector.

3D Mesh Encoder An Executor that receives Documents containing point sets data in its blob attribute, with shape (N, 3) and encodes it to embeddings o

Jina AI 11 Dec 14, 2022
missing-pixel-filler is a python package that, given images that may contain missing data regions (like satellite imagery with swath gaps), returns these images with the regions filled.

Missing Pixel Filler This is the official code repository for the Missing Pixel Filler by SpaceML. missing-pixel-filler is a python package that, give

SpaceML 11 Jul 19, 2022
GTK and Python based, simple multiple image editor tool

System Monitoring Center GTK3 and Python3 based, simple multiple image editor tool. Note: Development of this application is not completed yet. The ap

Hakan Dündar 1 Feb 02, 2022
Program for analyzing shadows from Cassini images

Moons: An Analysis Module for Vicar Files General This packages/program was created for my bachelor's thesis for the Astronomy department at Universit

Joni 1 Jul 16, 2021
Computer art based on joining transparent images

Computer Art There is no must in art because art is free. Introduction The following tutorial exaplains how to generate computer art based on a series

Computer Art 12 Jul 30, 2022
FrostedGlass is a translucent frosted glass effect widget, that creates a context with the background behind it.

FrostedGlass FrostedGlass is a translucent frosted glass effect widget, that creates a context with the background behind it. The effect is drawn on t

Kivy Garden 24 Dec 10, 2022
Alternate Python bindings for the Open Asset Import Library (ASSIMP)

Impasse A simple Python wrapper for assimp using cffi to access the library. Requires Python = 3.7. It's a fork of PyAssimp, Assimp's official Python

Salad Dais 3 Sep 26, 2022
An esoteric visual language that takes image files as input based on a multi-tape turing machine, designed for compatibility with C.

vizh An esoteric visual language that takes image files as input based on a multi-tape turing machine, designed for compatibility with C. Overview Her

Sy Brand 228 Dec 17, 2022
A sketch like(?) effect for images

lineArt A sketch like(?) effect for images How to run main.py [filename] [option {1,2}] option 1 retains colour option 2 gives gray image #results ori

1 Oct 28, 2021
Console images in 48 colors, 216 colors and full rgb

console_images Console images in 48 colors, 216 colors and full rgb Full RGB 216 colors 48 colors If it does not work maybe you should change color_fu

Урядов Алексей 5 Oct 11, 2022
A tool to maintain an archive/mirror of your Google Photos library for backup purposes.

Google Photos Archiver Updated Instructions 8/9/2021 Version 2.0.6 Instructions: Download the script (exe or python script listed below) Follow the in

Nick Dawson 116 Jan 03, 2023
Tools for making image cutouts from sets of TESS full frame images

Cutout tools for astronomical images Astrocut provides tools for making cutouts from sets of astronomical images with shared footprints. It is under a

Space Telescope Science Institute 20 Dec 16, 2022
👾 Python project to help you convert any image into a pixel art.

👾 Pixel Art Generator Python project to help you convert any image into a pixel art. ⚙️ Developer's Guide Things you need to get started with this co

Atul Anand 6 Dec 14, 2022
A warping based image translation model focusing on upper body synthesis.

Pose2Img Upper body image synthesis from skeleton(Keypoints). Sub module in the ICCV-2021 paper "Speech Drives Templates: Co-Speech Gesture Synthesis

zhiyh 15 Nov 10, 2022
Img-to-ascii-art - Converter of image to ascii art

img-to-ascii-art Converter of image to ascii art Latest Features. Intoducing Col

1 Dec 31, 2021
This piece of code is a User Welcomer with Image Manipulation using Python and Pillow (PIL).

This piece of code is a User Welcomer with Image Manipulation using Python and Pillow (PIL).

Bero 4 Jan 11, 2022
Blender addon to generate better building models from satellite imagery.

Blender addon to generate better building models from satellite imagery.

Ivan Ereshchenko 24 Apr 14, 2022
Generate different types of random avatars.

avatar-generator Generate different types of random avatars. Requirements Python3 pytorch=1.6 cv2=3.4 tqdm 1. Github-like avatars python generate_gi

Ming 11 Apr 02, 2022
Design custom QR codes with this web app!

My-QR.Art This web app lets users design their own QR codes to any domain. It can be acessed on my-qr.art. You can find some more background info abou

Marien Raat 406 Dec 20, 2022
利用近邻法的弱点实现图片缩小后变成另一张图

这是我一个视频的配套代码。 视频是:利用近邻法的弱点实现图片缩小后变成另一张图 https://www.bilibili.com/video/BV1Lf4y1r7dZ 配套代码中,仅generate.py是核心文件,其余的图片神马的,都是赠品。 这个核心文件利用了近邻法缩放的弱点,可以将图a的像素按

偶尔有点小迷糊 182 Dec 19, 2022