Skip to content

Instantly share code, notes, and snippets.

@aragaer
Last active October 30, 2018 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aragaer/fe33166edb088a81e8fb8b2ea6056e66 to your computer and use it in GitHub Desktop.
Save aragaer/fe33166edb088a81e8fb8b2ea6056e66 to your computer and use it in GitHub Desktop.
literate programming на питоне

Подготовительные вещи

РЕСЕТ СЕССИИ

(setq kill-buffer-query-functions
      (remq 'process-kill-buffer-query-function
            kill-buffer-query-functions))
(kill-buffer "wall")

Сначала надо выставить правильный virtualenv

(pyvenv-deactivate)
(pyvenv-activate (concat (file-name-directory (or load-file-name buffer-file-name)) ".venv"))

Поставить нужные пакеты

echo $VIRTUAL_ENV
which python
pip install --upgrade Pillow
pip install nose

Всякие очень нужные импорты

import os
import sys

import numpy as np

from PIL import Image

Константы

SIZE_X = 100
SIZE_Y = 100
OFFT_X = 50
OFFT_Y = 50

Функции для загрузки изображений

get_new_size

  • Возвращает новый размер для картинки.
  • Пропорции сохраняются.
  • x должен стать не менее SIZE_X
  • y должен стать не менее SIZE_Y
def get_new_size(x, y):
    ratio = max(SIZE_X / x, SIZE_Y / y)
    return int(x * ratio), int(y * ratio)

Тесты

from nose.tools import eq_
print("Running get_new_size tests")
eq_(get_new_size(SIZE_X, SIZE_Y), (SIZE_X, SIZE_Y))
eq_(get_new_size(SIZE_X, SIZE_Y*2), (SIZE_X, SIZE_Y*2))
eq_(get_new_size(SIZE_X*2, SIZE_Y), (SIZE_X*2, SIZE_Y))
eq_(get_new_size(SIZE_X*2, SIZE_Y*2), (SIZE_X, SIZE_Y))
eq_(get_new_size(SIZE_X*3, SIZE_Y*2), (SIZE_X*1.5, SIZE_Y))
print("get_new_size tests passed")

get_offsets

  • Принимает размер size_x, size_y
  • Возвращает список пар (x, y)
  • Первая пара должна быть 0, 0
  • Каждая последующая смещена либо по x, либо по y не более чем на OFFT_X/OFFT_Y
  • Для последней пары x+SIZE_X, y+SIZE_Y = size_x, size_y
# Беда - ob-python не работает с уменьшением индентации
# Приходится раскидывать по разным функциям
def _slide_x(x):
    return [(i*SIZE_X//2, 0) for i in range(x*2//SIZE_X-1)]

def _slide_y(y):
    return [(0, i*SIZE_Y//2) for i in range(y*2//SIZE_Y-1)]

def get_offsets(x, y):
    return _slide_x(x) if x > y else _slide_y(y)

Тесты

from nose.tools import eq_
print("Running get_offsets tests")
eq_(get_offsets(SIZE_X, SIZE_Y), [(0, 0)])
eq_(get_offsets(SIZE_X*3//2, SIZE_Y), [(0, 0), (SIZE_X//2, 0)])
eq_(get_offsets(SIZE_X*2, SIZE_Y), [(0, 0), (SIZE_X//2, 0), (SIZE_X, 0)])
eq_(get_offsets(SIZE_X, SIZE_Y*3//2), [(0, 0), (0, SIZE_Y//2)])
eq_(get_offsets(SIZE_X, SIZE_Y*2), [(0, 0), (0, SIZE_Y//2), (0, SIZE_Y)])
print("get_offsets tests passed")

load_image

def load_image(filename):
    image = Image.open(filename)
    image = image.resize(get_new_size(*image.size), Image.ANTIALIAS).convert("RGB")
    images = [image.crop((x, y, x+SIZE_X, y+SIZE_Y)) for x, y in get_offsets(*image.size)]
    return [np.array(i) / 128.0 - 1 for i in images]

Пробуем!

load_image(os.path.expanduser("~/Pictures/wallpapers/0002.jpg"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment