I wanted to change the image of my SNS account soon, so I did it in Python. Leave the code. The contents are the following three
--Load image --Output the image in monochrome --Output the image as dots
Will be. There is not much attention, but dot conversion will take some time. (About 1 minute? Depending on the specifications of the PC)
Please note the following points when executing by yourself.
--Upload the original image --Renamed image file in code (hereinafter referred to as shiro.jpg)
Prepare and load the image. I'm doing it on the Jupiter Notebook. In that case, prepare an image and upload it to Notebook in advance.
import numpy as np
import matplotlib.pyplot as plt
import cv2
#Loading images
img = plt.imread('shiro.jpg')
type(img)
img.size
plt.imshow(img) #Image display
plt.show()
This is the original image.
Next, monochrome (black and white) processing is performed and output.
def img_show(img : np.ndarray, cmap = 'gray', vmin = 0, vmax = 255, interpolation = 'none') -> None:
plt.imshow(img, cmap = cmap, vmin = vmin, vmax = vmax, interpolation = interpolation) #Display image
plt.show()
plt.close()
img = plt.imread('shiro.jpg')
img_mid_v = np.max(img, axis = 2)/2 +np.min(img, axis = 2)/2
img_show(img_mid_v)
img = plt.imread('shiro.jpg')
Make dots. It may be interesting to play with the numbers "dst = pixel_art (img, 0.1, 4)" as you like. When executed, a file such as'shiro_mozaiku.jpg' will be output to Jupiter Notebook.
#Color reduction processing
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))
#Mosaic processing
def mosaic(img, alpha):
h, w, ch = img.shape
img = cv2.resize(img,(int(w*alpha), int(h*alpha)))
img = cv2.resize(img,(w, h), interpolation=cv2.INTER_NEAREST)
return img
#Pixel art
def pixel_art(img, alpha=2, K=4):
img = mosaic(img, alpha)
return sub_color(img, K)
#Get input image
img = cv2.imread("shiro.jpg ")
#Pixel art Image roughness,Color roughness
dst = pixel_art(img, 0.1, 4)
#Output result
cv2.imwrite("shiro_mozaiku.jpg ", dst)
from PIL import Image
mozaiku_shiro = Image.open('shiro_mozaiku.jpg')
mozaiku_shiro
It feels like I've made something pretty good. This is a picture of when I went on a trip, but it seems that buildings such as castles can be converted into mosaic dots. Other than that, I don't know what will happen to people and landscapes, but it may be interesting to try it.
Recommended Posts