Preparation for processing pbm images on a pixel-by-pixel basis

Instead of processing the binary part of pbm yourself I thought it would be easy to write using the library, but numpy seems to be good.

It was good from pbm to ndarray, I don't know how to convert back from ndarray to binary pbm.

NumPy array and PIL conversion Add Star Although I referred to ↑ etc.

When returning an array of binary images to an image It is not pbm because the value is replaced with 1 of 8bit instead of 1bit. I wonder if pillow is not enough.

array_to_pbm.py


%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

#Open image file
file_name = 'lf_img_small.pbm'
lf_img = Image.open(file_name)
#In the case of a binary image, the value is stored as a bool type.
#In numpy the bool type is numpy.Defined as bool8.
#When reading into an array, specify bool8 as the read mode.
lf_img_ary = np.array(lf_img, np.bool8)

width, height = lf_img.size
print(width, height)

#Let's examine the features of the array.
print('****************')
print(img_ary.flags)
print(img_ary.ndim)
print(img_ary.size)
print(img_ary.shape)
print(img_ary.itemsize)
print(img_ary.strides)
print(img_ary.nbytes)
print(img_ary.dtype)
print('****************')
for x in range(height):
    for y in range(width):
        if y ==0 :
            print(img_ary[x,y])

#When converting to an image, it's like fromarray,
#If it is bool8, an error will occur.
Image.fromarray(np.bool8(img_ary)).save('ary_to_pbm_file.pbm')

#If uint8 is specified, pgm is created instead of pbm.
Image.fromarray(np.uint8(img_ary)).save('ary_to_pbm_file.pbm')

Recommended Posts

Preparation for processing pbm images on a pixel-by-pixel basis
I tried a TensorFlow tutorial (MNIST for beginners) on Cloud9-Classification of handwritten images-
A tool for creating symbolic links on Windows
Make a bot for Skype on EC2 (CentOS)
A memorandum for touching python Flask on heroku
Build a Kubernetes environment for development on Ubuntu