在宅勤務他で暇なので
ドット絵クイズを作ってみました。

問題の動画はこちら



ドット絵を作る
ソースコードはこちら
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
%matplotlib inline

def resize1(img):
    height, width = img.shape[:2]
    rate = 720 / height
    n_width = round(width * rate)
    size = (n_width,720)
    return cv2.resize(img, size)

def resize2(img):
    height, width = img.shape[:2]
    rate = 256 / height
    n_width = round(width * rate)
    size = (n_width,256)
    return cv2.resize(img, size)

def center_img(img):
    img2 = np.zeros((720, 1280, 3), np.uint8)
    height, width = img.shape[:2]
    img2[0:height, (1280-width)//2:(1280-width)//2+width] = img
    return img2

def sub_color(src, K):
    Z = src.reshape((-1, 3))
    Z = np.float32(Z)
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    ret, label, center = cv2.kmeans(
        Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
    center = np.uint8(center)
    res = center[label.flatten()]
    return res.reshape((src.shape))

def anime_filter(img, K):
    gray = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
    edge = cv2.blur(gray, (3, 3))
    edge = cv2.Canny(edge, 50, 150, apertureSize=3)
    edge = cv2.cvtColor(edge, cv2.COLOR_GRAY2BGR)
    img = sub_color(img, K)
    return cv2.subtract(img, edge)

def mosaic(src, ratio=0.25):
    small = cv2.resize(src, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_NEAREST)
    return cv2.resize(small, src.shape[:2][::-1], interpolation=cv2.INTER_NEAREST)

input_path = 'フォルダのパス'
file_name = 'ファイル名'
input_file_path = input_path + file_name

# ファイル読み込み
img = cv2.imread(input_file_path, cv2.IMREAD_COLOR)
# リサイズ
img = resize1(img)
# アニメ化
img = anime_filter(img, 16)
# モザイク処理(img,粒度)
img = mosaic(img,0.01)
# リサイズ2
img = resize2(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(figsize=(16,9))
ax.imshow(img)
plt.show()



download

やっていることは
画像を取り込んで
リサイズ加工し
ドット絵加工しています。

モザイクの粒度を変えれば、
もう少し判別できる形になります。
小さくすればするほど荒く
大きくすると細かくなります。

ぜひ挑戦してみてください。
分かった秒数を
コメント欄に是非!!!

それでは