2

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()
4
  • 2
    What do you mean by a binary image? Commented Feb 20, 2019 at 10:54
  • Please be more specific, do you want the image in a base64 string? Commented Feb 20, 2019 at 10:56
  • like including ones and zeros. Commented Feb 20, 2019 at 11:09
  • After I converted, I will count connected components with using levialdi’s shrinkink algorithm Commented Feb 20, 2019 at 11:11

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.