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]

以下のコードでは、入力写真を抽象化します。(ChatGPT Proにより生成)
import cv2
import numpy as np

# Load the original image
img = cv2.imread("your_image.jpg")

# Resize for faster processing (optional)
img = cv2.resize(img, (512, 512))

# Apply bilateral filter to smooth color while preserving edges
smoothed = cv2.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)

# Detect edges
gray = cv2.cvtColor(smoothed, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, threshold1=50, threshold2=150)

# Invert edges
edges_inv = cv2.bitwise_not(edges)

# Convert edges to 3 channels
edges_colored = cv2.cvtColor(edges_inv, cv2.COLOR_GRAY2BGR)

# Merge edge mask and smoothed image
abstract = cv2.bitwise_and(smoothed, edges_colored)

# Show results
cv2.imshow("Original", img)
cv2.imshow("Abstract", abstract)
cv2.waitKey(0)
cv2.destroyAllWindows()

以下のコードでは、現画像をグレースケールか、1か0のモノクロームに変換します。

from PIL import Image

# 元画像の読み出し

im =Image.open('myimage.JPG')

# グレースケール変換

im_grayscale = im.convert('L')

im_grayscale.save('image_grayscale .png')

# モノクローム変換

im_monochrome = im_grayscale.convert('1')

print(type(im_monochrome))

# ファイルの保存

#im_monochrome.save('image_monochrome.jpg', quality=95)

im_monochrome.save('image_monochrome.png') 

[6]のように、Pythonを使って直接Excelファイルを操作することができます。 

PythonコードをExcelに埋め込むこともできます[7]。


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

No comments:

Post a Comment