基礎ユニット2(イメージメディア) 第8回(2018/11/29)

関連サイトと資料

サンプル画像

building.jpg

butterfly.jpg

fruits.jpg

kabayaki.png

サンプルプログラム

mosaic1.py
import cv2
	
# パラメータ
target = 'building.jpg'
block_size = 20
	
# 処理
img = cv2.imread(target, cv2.IMREAD_COLOR)
height, width, _ = img.shape
img2 = cv2.resize(img, (int(width/block_size), int(height/block_size)), interpolation=cv2.INTER_NEAREST)
img3 = cv2.resize(img2, (width, height), interpolation=cv2.INTER_NEAREST)
	
# 表示
cv2.imshow('Original', img)
cv2.imshow('Result', img3)
	
cv2.waitKey(0)
cv2.destroyAllWindows()

mosaic2.py
import cv2
	
# パラメータ
target = 'building.jpg'
block_size = 20
	
# 処理
img = cv2.imread(target, cv2.IMREAD_COLOR)
img2 = cv2.resize(img, None, fx = 1/block_size, fy = 1/block_size, interpolation=cv2.INTER_NEAREST)
img3 = cv2.resize(img2, None, fx = block_size, fy = block_size, interpolation=cv2.INTER_NEAREST)
	
# 表示
cv2.imshow('Original', img)
cv2.imshow('Result', img3)
	
cv2.waitKey(0)
cv2.destroyAllWindows()

mosaic3.py
import cv2

def mosaic(orgImg, bs):
	関数の中身は各自で考える!
	
# パラメータ
target = 'building.jpg'
block_size = 20
	
# 処理
img = cv2.imread(target, cv2.IMREAD_COLOR)
imgMosaic = mosaic(img, block_size)
	
# 表示
cv2.imshow('Original({0})'.format(target), img)
cv2.imshow('Result({0}, block_size={1})'.format(target, block_size), imgMosaic)
	
cv2.waitKey(0)
cv2.destroyAllWindows()

mosaic4.py
import cv2

def mosaic(orgImg, bs):
	関数の中身は各自で考える!
	
# パラメータ
target = 'building.jpg'
	
# 処理
win_names = []
processed_images = []
img = cv2.imread(target, cv2.IMREAD_COLOR)
for block_size in range(10, 60, 10):
    imgMosaic = mosaic(img, block_size)
    processed_images.append(imgMosaic)
    win_names.append('Result({0}, block_size={1})'.format(target, block_size))
	
# 表示
cv2.imshow('Original({0})'.format(target), img)
for i in range(len(win_names)):
    cv2.imshow(win_names[i], processed_images[i])
	
cv2.waitKey(0)
cv2.destroyAllWindows()

listup1.py
import os
import glob
	
path = 'D:\\Python2019\\KisoUnit2\\20181129\\処理対象\\*.*'
files = glob.glob(path)
	
for f in files:
    f1, f2 = os.path.split(f)
    f3, f4 = os.path.splitext(f2)
    print(f, f1, f2, f3, f4)

mosaic7.py
import os
import glob
import cv2
import numpy as np
	
def mosaic(orgImg, bs):
	関数の中身は各自で考える!
	
# パラメータ
path = 'D:\\Python2019\\KisoUnit2\\20181129\\処理対象\\*.*'
block_size = 20
	
# 処理
files = glob.glob(path)
for f in files:
    f1, f2 = os.path.split(f)
    f3, f4 = os.path.splitext(f2)
    savename = f3 + '_M{0}'.format(block_size) + f4
    print(f + ' ---> ' + savename)
    
    # ファイルパスに日本語が含まれていると、通常のcv2.imreadでは読み込みに失敗する!
    # img = cv2.imread(f, cv2.IMREAD_COLOR)
    n = np.fromfile(f, np.uint8)
    img = cv2.imdecode(n, cv2.IMREAD_COLOR)
	
    imgMosaic = mosaic(img, block_size)
    cv2.imwrite(savename, imgMosaic)