Home > Software design >  How to convert image to [1,0,0,1,0] pixel array with Python?
How to convert image to [1,0,0,1,0] pixel array with Python?

Time:06-10

I've been trying to solve this Python problem for the last 4 days... I have a black and white image (.png or .jpg), for example: image example

I would like to load it (let's call it "heart.png") and convert it to the following array format:

[1,1,0,1,1,1,0,1,1,1],
[1,0,0,0,1,0,0,0,1,1],
[0,1,1,1,0,1,1,1,0,1],
[0,1,1,1,1,1,1,1,0,1],
[0,1,1,1,1,1,1,1,0,1],
[0,1,1,1,1,1,1,1,0,1],
[1,0,1,1,1,1,1,0,1,1],
[1,1,0,1,1,1,0,1,1,1],
[1,1,1,0,0,0,1,1,1,1],
[1,1,1,1,0,1,1,1,1,1],

In words: I would like to analyse every single pixel in every row and convert it to a matrix that writes white as "1" and black as "0" (or the other way around..doesn't matter, because I can invert colours before), divided by comma between pixels, every row should be hold in square brackets and also divided by comma.

I really need help with this, I think OpenCV could solve this but I don't know how...

Thanks in advance!

CodePudding user response:

You can use OpenCV and Numpy to read the image, assuming your image is grayscale with just black and white colors.

import numpy as np
import cv2

img = cv2.imread("your-image-here.png", cv.IMREAD_GRAYSCALE) # The image pixels have range [0, 255]
img //= 255  # Now the pixels have range [0, 1]
img_list = img.tolist() # We have a list of lists of pixels

result = ""
for row in img_list:
    row_str = [str(p) for p in row]
    result  = "["   ", ".join(row_str)   "],\n"

If your image is more complicated than what you posted in your question then you should probably use more advanced techniques such as thresholding.

  • Related