bufferoverflow
bufferoverflow

Reputation: 81

How to read the file and convert it to a binary image in Python

I am new to Python, I want to read a image like jpg,png. and convert it to binary image. Here is my work:

from PIL import Image
import numpy



def main( ):
    name= 'b.jpg'

    img= Image.open (name);
    for pixel in iter(img.getdata()):
        print(pixel)

    img.convert("1").show();

    del image;

if __name__=='__main__':
    main()

Upvotes: 2

Views: 27895

Answers (1)

JAbr
JAbr

Reputation: 332

This could be your solution:

# Read Image 
img= Image.open(file_path)  
# Convert Image to Numpy as array 
img = np.array(img)  
# Put threshold to make it binary
binarr = np.where(img>128, 255, 0)
# Covert numpy array back to image 
binimg = Image.fromarray(binarr)

Upvotes: 5

Related Questions