Tuesday, February 19, 2019

Python Memo パイソンの学習メモ

 Python(パイソン)は、オランダ人のグイド・ヴァンロッサムによって開発されたオープンソースのオブジェクト指向スクリプト言語。イギリスのテレビ局 BBC が製作したコメディ番組『空飛ぶモンティ・パイソン』にちなんで名付けられた。Pythonという英単語は爬虫類のニシキヘビを意味し、Python言語のマスコットやアイコンとして使われることがある(wikipedia)。
Windows版はこちらから直接ダウンロードできます。

 Opencvを使う画像処理については、「【Python/OpenCV】画像処理入門・サンプル集」はよい学習材料です。

(2019年1月更新)
今は、AnacondaやConda、MiniCondaは一番簡単に使える環境です。

Windows環境でのファイル処理では、まずエンコードを正しく指定しないと、すぐエラーになります。例えば、UTF-8 with BOM(UTF-8-BOM)でエンコードされたテキストファイルを開く場合、以下のように指定する必要はあります。
  io.open(filename, "r", encoding="utf_8_sig")

str型(UTF-8)からunicode型に変換には、[1]

  uni_string = unicode(str_string, 'utf_8_sig')

 Python Imaging Library (PIL)と併用すれば、画像処理のプログラムだって簡単に書けます。
以下のスクリプトでは、Fractal(フラクタル)画像を作成する例です。
#!/usr/bin/python
import Image, ImageDraw, math, colorsys
dimensions = (800, 800)
scale = 1.0/(dimensions[0]/3)
center = (2.2, 1.5)       # Use this for Mandelbrot set
#center = (1.5, 1.5)       # Use this for Julia set
iterate_max = 100
colors_max = 50
img = Image.new("RGB", dimensions)
d = ImageDraw.Draw(img)
# Calculate a tolerable palette
palette = [0] * colors_max
for i in xrange(colors_max):
    f = 1-abs((float(i)/colors_max-1)**15)
    r, g, b = colorsys.hsv_to_rgb(.66+f/3, 1-f/2, f)
    palette[i] = (int(r*255), int(g*255), int(b*255))
# Calculate the mandelbrot sequence for the point c with start value z
def iterate_mandelbrot(c, z = 0):
    for n in xrange(iterate_max + 1):
        z = z*z +c
        if abs(z) > 2:
            return n
    return None
# Draw our image
for y in xrange(dimensions[1]):
    for x in xrange(dimensions[0]):
        c = complex(x * scale - center[0], y * scale - center[1])
        n = iterate_mandelbrot(c)            # Use this for Mandelbrot set
        #n = iterate_mandelbrot(complex(0.3, 0.6), c)  # Use this for Julia set
        if n is None:
            v = 1
        else:
            v = n/100.0
        d.point((x, y), fill = palette[int(v * (colors_max-1))])
del d
img.save("result.png")
以下は上のスクリプトで作成されたMandelbrotとJuliaフラクタル画像です。
PythonとPILライブラリで作成したJuliaフラクタル
PythonとPILライブラリで作成したMandelbrotフラクタル
以下は参考リンク[2]の「領域分割で減色」で処理した原画像と結果例です。
写真のアニメ絵化の結果
原画像(This person does not existプログラムで生成)

adaptiveThresholdを使ったエッジ抽出による結果
モルフォロジー変換のMORPH_OPENを使ってエッジを強調した[4]

参考リンク
[1] PythonでUTF-8 with BOMを開く
[2] 【Python/OpenCV】画像処理入門・サンプル集
[3]【Python/OpenCV】写真のアニメ絵化
[4] モルフォロジー変換
[5] python-izm:独学の無料サイト

No comments:

Post a Comment