简体   繁体   中英

Python read if image pixel is black or white

I have done some googling and haven't been able to find any working solution to my problem. I am trying to write a program that will take a black and white image and store in an array whether the pixel is black or white.

I have been able to open the image and read the width and height of it but am completely stuck as to how to detect if the pixel is black or white and then store that in an array for later use.

I have been using the following code and any help would be great. I ideally would want to read if the pixel is white and store that as a 1 in the array map.

from PIL import Image
import numpy as np
from scipy import misc
from pandas import *

##Opens the Image
im_file = Image.open('mazes/15x15.png')


##Reads the image pixel information
arr = np.array(im_file)

##Sets the width, height and maze size variables
width = im_file.size[0]
height = im_file.size[1]
size = width * height

##Defines the mapping array
map = np.zeros([width, height], dtype=np.int)

##Prints maze information for debugging
print ('Maze width:', width)
print ('Maze height:', height)
print ('Maze size:', size, '\n')

##Prints mapping array for debugging
print (DataFrame(map))

If the image is not a grayscale image, either convert the image to a black and white image usually by pixel = (R+G+B)/3 or use skimage.io's imread function with as_grey = True.

Each pixel in the image now has a value between being fully black and being fully white. Either you can set a threshold by hand and classify all pixels whose value is above this value as 'white' using the numpy.where or you can use skimage's built in thresholding filters depending on what you really need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM