Convert a black and white image to array of numbers? Convert a black and white image to array of numbers? numpy numpy

Convert a black and white image to array of numbers?


I would recommend to read in images with opencv. The biggest advantage of opencv is that it supports multiple image formats and it automatically transforms the image into a numpy array. For example:

import cv2import numpy as npimg_path = '/YOUR/PATH/IMAGE.png'img = cv2.imread(img_path, 0) # read image as grayscale. Set second parameter to 1 if rgb is required 

Now img is a numpy array with values between 0 - 255. By default 0 equals black and 255 equals white. To change this you can use the opencv built in function bitwise_not:

img_reverted= cv2.bitwise_not(img)

We can now scale the array with:

new_img = img_reverted / 255.0  // now all values are ranging from 0 to 1, where white equlas 0.0 and black equals 1.0 


Load the image and then just invert and divide by 255.

Here is the image ('Untitled.png') that I used for this example: https://ufile.io/h8ncw

import numpy as npimport cv2import matplotlib.pyplot as pltmy_img = cv2.imread('Untitled.png') inverted_img = (255.0 - my_img)  final = inverted_img / 255.0# Visualize the resultplt.imshow(final)plt.show()print(final.shape)(661, 667, 3)

Results (final object represented as image):

final image


You have to load the image from the path and then transform it to a numpy array.

The values of the image will be between 0 and 255. The next step is to standardize the numpy array.

Hope it helps.