物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

PythonでJPGの2値画像をPNG画像に変換する

元々2値のPNG画像を無理やりJPG画像にすると、アナログノイズ的に輝度値が揺らいでしまう。 また、JPG画像の方が画像サイズが増えてしまうこともある。 JPG画像にしても輝度値は大きく変わらないので、閾値127で2値画像を作り、PNG形式で保存する関数を作った。

# %%
import cv2

def GetBinaryPng(jpgfile, pngfile, showhist=False):
    img = cv2.imread(jpgfile,0)
    hist = cv2.calcHist([img],[0],None,[256],[0,256])
    if showhist:
        import matplotlib.pyplot as plt
        plt.bar([i for i in range(256)], [a[0] for a in hist], width=1.0)
        plt.yscale('log')
        plt.show()

    ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
    cv2.imwrite(pngfile, thresh1)

# %%
for i in range(0, 30):
    GetBinaryPng(f"{i}.jpg",f"{i}.png")
# %%