PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How to convert image to [1,0,0,1,0] pixel array with Python?

 July 30, 2022     arrays, image, opencv, pixel, python     No comments   

Issue

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!


Solution

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.



Answered By - FrontBack
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing