Pythonの標準ライブラリには、強力で十分な画像操作コードは付属していませんが、インストールと使用が簡単な代替手段がいくつかあります。PILを使用してこれを行う方法を示します。
from PIL import Image
def randomStars(small, large):
import random
filename = pickAFile()
pic = Image.open(filename)
max_x, max_y = pic.size
pixels = im.load()
x = random.randrange(max_x)
y = random.randrange(max_y)
for i in range(max_x):
for j in range(max_y):
if random.random() < 0.25:
red = random.randint(256)
green = random.randint(256)
blue = random.randint(256)
pixels[i, j] = (red, green, blue, 1)
im.show()
このshow
関数はアプリに画像を表示しません(そのためには、tkinter
またはのようなイベントループを備えたある種のGUIが必要ですPySide
)。ファイルを一時ディレクトリに保存し、プレビューやxvなどのプラットフォーム固有のプログラムを実行して表示します。
あなたもファイルを保存したいと思うでしょう。それも簡単です:
name, ext = os.path.splitext(filename)
outfilename = '{}-with-stars.{}'.format(name, ext)
im.save(outfilename)
これにより、デフォルトのJPEG設定で.jpgに保存され、ファイル名から必要なものを推測するPILに依存します。(つまり、はい、を使用するだけでPNGとして保存できます'{}-with-stars.png'.format(name)
。)より詳細な制御が必要な場合は、明示的な形式と形式固有のオプションを指定して、PILでもそれを実行できます。
これまでのところ、これは既存のコードを機能するものに変換する方法であり、それを試してデバッグを開始できます。それは実際には元の問題に答えるものではありません。
この写真の空にランダムな数(mからnまで)の星を作成する関数を書きたい
したがって、最初に、すべてのピクセルにわたるループではなく、ループとしてこれが必要です。
for _ in random.randint(m, n):
今:
星は、単一の白いピクセル、または4つの隣接する白いピクセルの正方形のいずれかでランダムに構成される必要があります。
x, y = random.randrange(max_x), random.randrange(max_y)
if random.random() < .5:
# draw white pixel at [x, y]
pixels[x, y] = (1, 1, 1, 1)
else:
# draw square at [x, y], making sure to handle edges
また、木の枝、月、鳥の上に「星」(1ピクセル)を配置したくありません。
木の枝、月、または鳥の一部をどのように知るかを定義する必要があります。ピクセルの色でそれを定義できますか?
一見すると、できるかもしれません。月のピクセルはすべて、他のどのピクセルよりも明るく、飽和度が高く、赤に偏っています(さらに明るいコーナーのAPロゴを除く)。鳥と枝は何よりも暗いです。実際、それらは非常に明確であるため、おそらく正しい色空間計算を行うことを心配する必要はありません。それはこのようなもののように単純かもしれません:
r, g, b, a = pixels[x, y]
fake_brightness = r+g+b+a
if fake_brightness < 0.2:
# Tree or bird, pick a new random position
elif 1.2 < fake_brightness < 2.8:
# Moon, pick a new random position
else:
# Sky or API logo, scribble away
(これらの数値は明らかに薄い空気から引き出されたものですが、少し試行錯誤することで使用可能な値が得られるはずです。)
もちろん、これを学習演習として行う場合は、この画像が非常に単純に解析可能であることに依存するのではなく、正しい色空間の計算を学習し、エッジ検出アルゴリズムを作成することもできます。