Python独習!

習得したPython知識をペイフォワード

Pythonで同心円のグラデーション画像を作る

数年前に先輩から同心円の画像を作るツールがないか聞かれたことがあった。当時は心当たりがなかったのでその先輩の力になれなかった。今になって思いだしたため、Pythonで挑戦してみた。

以前つくった『Sin波のグラデーション画像を作る』プログラムをベースにした。
greenhornprofessional.hatenablog.com

結果

画像輝度値をコサイン状に可変させた同心円の画像ができた。
f:id:greenhornprofessional:20200325210932j:plain

ラインプロファイル(画像上の黒線の断面)を見ても、それっぽくできている。
f:id:greenhornprofessional:20200325211204p:plain

プログラム

# 18_ConcentricCircles_001.py
# python 3.8.1
# coding: utf-8
#
import numpy as np
import cv2

pix = 512       #画像のサイズ
f = 20          #周期

img = np.zeros((pix,pix,1),np.uint8)    #空の2次元リストを定義。グレースケール。

#画像のサイズを0を中心に均等に割り振る。
pix_plus  = int(pix/2 + 1)
pix_minus = int(-pix/2 + 1)

#画像座標(左上が0, 右+, 下+)に振りなおすためのオフセット値
offset = int(pix/2 -1)

#The fisrt quadrant
for y in range(0, pix_plus):
    for x in range(0, pix_plus):
        z = 100 * np.cos(np.sqrt(x**2 + y**2) / f) + 120  
        img[x+offset][y+offset] = z

#The second quadrant
for y in range(0, pix_plus):
    for x in range(pix_minus, 0):
        z = 100 * np.cos(np.sqrt(x**2 + y**2) / f) + 120
        img[x+offset][y+offset] = z

#The third quadrant
for y in range(pix_minus, 0):
    for x in range(pix_minus, 0):
        z = 100 * np.cos(np.sqrt(x**2 + y**2) / f) + 120
        img[x+offset][y+offset] = z

#The fourth quadrant
for y in range(pix_minus, 0):
    for x in range(0, pix_plus):
        z = 100 * np.cos(np.sqrt(x**2 + y**2) / f) + 120
        img[x+offset][y+offset] = z

#imgを画像として保存
cv2.imwrite('Circle_512_512.jpg', img)
/* -----codeの行番号----- */