Created
August 23, 2016 11:36
-
-
Save hideyukisaito/d997ece5253286685f8c0189108acc19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import numpy as np | |
import cv2 | |
import math | |
def rgb_to_hsv(r, g, b): | |
hsv = cv2.cvtColor(np.array([[[b, g, r]]], dtype=np.uint8), cv2.COLOR_BGR2HSV)[0][0] | |
return (hsv[0], hsv[1], hsv[2]) | |
def main(): | |
# 画像を読み込む | |
img = cv2.imread('images/sample_7.jpg') | |
# 幅500pxを基準にリサイズ | |
scale = 500 / img.shape[1] | |
resized_img = cv2.resize(img, (round(img.shape[1] * scale), round(img.shape[0] * scale))) | |
height, width, channels = resized_img.shape | |
# 縦横の分割数とセルのサイズを決定 | |
div_y = 16 | |
div_x = 16 | |
cell_height, cell_width = round(height / div_y), round(width / div_x) | |
# 結果用の画像を生成 | |
canvas = np.zeros([cell_height * div_y, cell_width * div_x, channels], 'uint8') | |
for y in range(div_y): | |
for x in range(div_x): | |
pos_y = cell_height * y | |
pos_x = cell_width * x | |
# 平均化対象のセル | |
target = resized_img[pos_y:pos_y + cell_height, pos_x:pos_x + cell_width] | |
# 平均化 | |
averaged_color_per_row = np.average(target, axis=0) | |
averaged_color = np.average(averaged_color_per_row, axis=0).astype('uint8') | |
averaged_img = np.array([[averaged_color] * cell_width] * cell_height, np.uint8) | |
# HSVに変換 | |
hsv = rgb_to_hsv(averaged_color[2], averaged_color[1], averaged_color[0]) | |
# 閾値以上のセルを描画する | |
if hsv[0] in range(11, 100) and hsv[1] > 60 and hsv[2] > 80: | |
canvas[pos_y:pos_y + cell_height, pos_x:pos_x + cell_width] = averaged_img | |
# ウインドウに表示 | |
cv2.imshow('original', resized_img) | |
cv2.imshow('processed', canvas) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment