0

Im trying to convert the numpy array of the PIL image I got to a binary one but anything I have tried doesn't work. this is what I got so far:

from PIL import Image 
import numpy as np
pixels=np.array(Image.open("covid_encrypted_new.png").getdata())
def to_bin(pixels):
    return [format(i,"08b") for i in pixels]

also when I tried to iterate over the array and change each value to type bin it also didnt go well for me. What else can I try? thanks

Edwin Cheong
  • 879
  • 2
  • 7
  • 12
  • Data is already stored in a binary format, as a matrix of numbers. In the case of Pillow, it uses uint8 (unsigned int with 8 bits). What are you trying to do? Are you trying to print the image in a text format? – Gabriel A. Apr 16 '21 at 00:05
  • What do you expect the result to look like for a 3-pixel high by 1-pixel wide image where the top pixel is black, the middle pixel is mid-grey and the bottom pixel is white? Please click `edit` and add that into your question - not the comments. Thank you. – Mark Setchell Apr 16 '21 at 14:57

1 Answers1

2

This could be what your looking for

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

# 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)

You could even use opencv to convert

img = np.array(Image.open(file_path))
_, bin_img = cv2. threshold(img,127,255,cv2.THRESH_BINARY)
Edwin Cheong
  • 879
  • 2
  • 7
  • 12