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

  • Возможно, переписать в консольную утилиту, которой на вход подаются имена исходного изображения и результата. Сейчас чтобы заставить код работать с другой картинкой, его надо исправлять.
Seeks to remove text from an image in a convincing way.

Text-Removal This is a Computer Vision project that seeks to successfully remove text from an image by covering the text areas in a convincing way. He

6 Nov 22, 2022
Quickly 'anonymize' all people in an image. This script will put a black bar over all eye-pairs in an image

Face-Detacher Quickly 'anonymize' all people in an image. This script will put a black bar over all eye-pairs in an image This is a small python scrip

Don Cato 1 Oct 29, 2021
Rembg is a tool to remove images background.

Rembg is a tool to remove images background.

Daniel Gatis 7.8k Jan 05, 2023
Python modules to work with large multiresolution images.

Large Image Python modules to work with large, multiresolution images. Large Image is developed and maintained by the Data & Analytics group at Kitwar

Girder 136 Jan 02, 2023
ModernGL is a python wrapper over OpenGL 3.3+ core

ModernGL is a python wrapper over OpenGL 3.3+ core that simplifies the creation of simple graphics applications like scientific simulations, games or user interface

ModernGL 1.4k Jan 01, 2023
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
Convert HDR photos taken by iPhone 12 (or later) to regular HDR images

heif-hdrgainmap-decode Convert HDR photos taken by iPhone 12 (or later) to regular HDR images. Installation First, make sure you have the following pa

Star Brilliant 5 Nov 13, 2022
Plots the graph of a function with ASCII characters.

ASCII Graph Plotter Plots the graph of a function with ASCII characters. See the change log here. Developed by InformaticFreak (c) 2021 How to use py

InformaticFreak 2 Apr 29, 2022
Command line utility for converting images to seamless tiles

img2texture Command line utility for converting images to seamless tiles. The resulting tiles can be used as textures in games, compositing and 3D mod

Artёm IG 24 Dec 26, 2022
BeeRef — A Simple Reference Image Viewer

BeeRef — A Simple Reference Image Viewer BeeRef lets you quickly arrange your reference images and view them while you create. Its minimal interface i

Rebecca 245 Dec 25, 2022
Gallery written in Python to manage your photos

GalleryMan Gallery written in Python to manage your photos Installation

Asian Cat 24 Dec 18, 2022
The InvGears workbench for FreeCAD allows the creation of gear systems

FreeCAD InvGears workbench Current version 0.1.1 Overview The InvGears workbench allows the creation of gear systems. The gear generation algorithm is

Sebastian Ernesto Garcia 8 Dec 10, 2021
a lite weight photo editor written in python for day to day photo editing!

GNU-PhotoShop A lite weight Photo editing Program (currently CLI only) written in python3 for day to day photo editing. Disclaimer : Currently we don'

Kunal Sharma 5 May 30, 2022
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
🖼️ Draw Images or GIFs in your terminal

Drawitor Draw Images/GIFs in your terminal. Install pip install drawitor CLI Tool drawitor cat_dancing.gif Library The library is written in a simple

Eliaz Bobadilla 7 Dec 15, 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
Group of interfaces interesting for users

Project: Interface to create GIF animation based on Fourier Series.

5 Aug 17, 2021
Png-to-stl - Converts PNG and text to SVG, and then extrudes that based on parameters

have ansible installed locally run ansible-playbook setup_application.yml this sets up directories, installs system packages, and sets up python envir

1 Jan 03, 2022
PyLibTiff - a wrapper to the libtiff library to Python using ctypes

PyLibTiff is a package that provides: a wrapper to the libtiff library to Python using ctypes. a pure Python module for reading and writing TIFF and L

Pearu Peterson 105 Dec 21, 2022
QSIprep: Preprocessing and analysis of q-space images

QSIprep: Preprocessing and analysis of q-space images Full documentation at https://qsiprep.readthedocs.io About qsiprep configures pipelines for proc

Lifespan Informatics and Neuroimaging Center 88 Dec 15, 2022