Pythonで画像をASCII画像に変換する
この記事では、特定の画像をASCII画像とも呼ばれるテキストベースの画像に変換します。
以下は、入力画像とさまざまな関数を取得してそれらをグレースケール画像に変換し、ASCII文字を適用してさまざまなパターンを作成して画像を挿入するPythonプログラムです。最後に、電子メールにはテキストベースの画像が届きます。これは一連のプレーンASCII文字です。
例
from PIL import Image
import os
ASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']
def resize_image(image, new_width=25):
(input__width, input__height) = image.size
aspect_ratio = input__height/float(input__width)
changed_height = int(aspect_ratio * new_width)
changed_image = image.resize((new_width, changed_height))
return changed_image
def make_grey(image):
return image.convert('L')
def pixel_to_ascii(image, range_width=25):
pixels_in_image = list(image.getdata())
pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value in
pixels_in_image]
return "".join(pixels_to_chars)
def image_to_ascii(image, new_width=25):
image = resize_image(image)
image = make_grey(image)
pixels_to_chars = pixel_to_ascii(image)
len_pixels_to_chars = len(pixels_to_chars)
image_ascii = [pixels_to_chars[index: index + new_width] for index in
range(0, len_pixels_to_chars, new_width)]
return "\n".join(image_ascii)
def convert_image(image_filepath):
# image = None
try:
image = Image.open(image_filepath)
except Exception as e:
print("Unable to open image file {image_filepath}.".format(image_filepath=image_filepath))
print(e)
return
image_ascii = image_to_ascii(image)
f = open(os.path.splitext(image_filepath)[0]+'.txt','w')
f.write(image_ascii)
f.close()
convert_image('D:\\button.jpg') 出力
上記のコードを実行すると、次の結果が得られます-
入力画像
出力画像
-
Pythonでのフォトモザイクの実装
フォトモザイクは、画像を正方形のグリッドに分割できる手法です。各正方形は、他の画像や色に置き換えられます。したがって、実際の画像を特定の距離から見たい場合は実際の画像を見ることができますが、近づくと、さまざまな色のブロックのグリッドを見ることができます。 この場合、photomosaicと呼ばれるPythonモジュールを使用しています。このモジュールを使用すると、いくつかのフォトモザイクを簡単に作成できます。インストールするには、このリンクをたどってください。 scikit learnもダウンロードします モジュール。 sudo pip3 install photomosaic この
-
Pythonで太陽画像をプロットする
Pythonでは、ソーラーイメージを作成するためのSunPyパッケージを提供しています。このパッケージには、さまざまな太陽観測所や太陽実験室からの陽子/電子フラックスの太陽データであるさまざまなファイルが含まれています。 pip install sunpyを使用する コマンド、sunpyパッケージをインストールできます。 ここでは、サンプルのAIA画像をプロットします。 AIAはAtmosphericImagingAssemblyです。これはSDOのもう1つの計器盤です。 ここでは、sunpy.Map()関数を使用して、サポートされているデータ製品の1つからマップを作成します。 サンプ