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 этап

  • Возможно, переписать в консольную утилиту, которой на вход подаются имена исходного изображения и результата. Сейчас чтобы заставить код работать с другой картинкой, его надо исправлять.
HtmlWebShot - A python3 package which Can Create Images From url, Html-CSS, Svg and from any readable file and texts with many setup features.

A python3 package which Can Create Images From url, Html-CSS, Svg and from any readable file and texts with many setup features

Danish 24 Dec 14, 2022
Tool to create a Phunk image with a custom background

Create Phunk image Tool to create a Phunk image with a custom background Installation Clone the repo git clone https://github.com/albanow/etherscan_sa

Albano Pena Torres 6 Mar 31, 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
DrawBot is a powerful, free application for macOS that invites you to write Python scripts to generate two-dimensional graphics

DrawBot is a powerful, free application for macOS that invites you to write Python scripts to generate two-dimensional graphics.

Frederik Berlaen 344 Jan 06, 2023
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
Extracts dominating colors from an image and presents them as a palette.

ColorPalette A simple web app to extract dominant colors from an image. Demo Live View it live at : https://colorpalettedemo.herokuapp.com/ You can de

Mayank Nader 214 Dec 29, 2022
Remove Background from Image With Python

Install Library pypi $ pip3 install xremovebg

krypton 4 May 26, 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
An API that renders HTML/CSS content to PNG using Chromium

html_png An API that renders HTML/CSS content to PNG using Chromium Disclaimer I am not responsible if you happen to make your own instance of this AP

10 Aug 08, 2022
Blender addon - convert empty image reference to image plane

Reference to image plane Convert reference images to a textured image mesh plane. As if it was imported with import image as plane Use on drag'n'dropp

Samuel Bernou 6 Nov 25, 2022
An add to make adding screenshots and copied images to the scene easy

Blender Clipboard to Scene It doesn't work with version 2.93 and higher (I tested it on 2.91 and 2.83) There is an issue with importing the Pillow mod

Mohammad Mehdi Afkhami 3 Dec 29, 2021
An application that maps an image of a LaTeX math equation to LaTeX code.

Convert images of LaTex math equations into LaTex code.

1.3k Jan 06, 2023
SimpleITK is an image analysis toolkit with a large number of components supporting general filtering operations, image segmentation and registration

SimpleITK is an image analysis toolkit with a large number of components supporting general filtering operations, image segmentation and registration

672 Jan 05, 2023
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
🎶😤 Generate an image indicating what you are listening to 😳

I'm Listening to This (song that I've sent you an image about detailing its metadata in a nifty way) Few lines describing your project. 📝 Table of Co

Connor B - Viibrant 4 Nov 03, 2021
Simple program to easily view Euler parameters in 3D.

Simple program to easily view Euler parameters in 3D.

5 Aug 20, 2021
Rotates your images in the spirit of rot13

Image Rotator (imrot10) Its like rot13 but for images. Calling the algorithm imrot10 for im = image, rot = rotation, 10 = default magnitude. Unfortuna

Sarah 2 Dec 10, 2021
python binding for libvips using cffi

README PyPI package: https://pypi.python.org/pypi/pyvips conda package: https://anaconda.org/conda-forge/pyvips We have formatted docs online here: ht

libvips 467 Dec 30, 2022
image-processing exercises.

image_processing Assignment 21 Checkered Board Create a chess table using numpy and opencv. view: Color Correction Reverse black and white colors with

Benyamin Zojaji 25 Dec 15, 2022