将黑白图像转换为数字数组?

Sam*_*One 6 python numpy image image-processing cv2

图像为28像素x 28像素。 他们可以将其解释为大量的数字: 像以上说明的图像,我怎样才能将图像转换到左边成代表之间的图像的暗度的阵列0 for whitedecimals for darker colours closer to 1? as shown in the image using蟒3`?

更新:我已经尝试在此方面做更多的工作。下面也有很好的答案。

# Load image 
filename = tf.constant("one.png")
image_file = tf.read_file(filename)

# Show Image
Image("one.png")

#convert method
def convertRgbToWeight(rgbArray):
    arrayWithPixelWeight = []
    for i in range(int(rgbArray.size / rgbArray[0].size)):
        for j in range(int(rgbArray[0].size / 3)):
            lum = 255-((rgbArray[i][j][0]+rgbArray[i][j][1]+rgbArray[i][j][2])/3) # Reversed luminosity
            arrayWithPixelWeight.append(lum/255) # Map values from range 0-255 to 0-1

    return arrayWithPixelWeight



# Convert image to numbers and print them
image_decoded_png = tf.image.decode_png(image_file,channels=3)
image_as_float32 = tf.cast(image_decoded_png, tf.float32)

numpy.set_printoptions(threshold=numpy.nan)
sess = tf.Session()
squeezedArray = sess.run(image_as_float32)

convertedList = convertRgbToWeight(squeezedArray)

print(convertedList) # This will give me an array of numbers. 
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 6

我建议使用opencv读取图像。opencv的最大优点是它支持多种图像格式,并且可以自动将图像转换为numpy数组。例如:

import cv2
import numpy as np

img_path = '/YOUR/PATH/IMAGE.png'
img = cv2.imread(img_path, 0) # read image as grayscale. Set second parameter to 1 if rgb is required 
Run Code Online (Sandbox Code Playgroud)

现在img是一个numpy数组,其值介于之间0 - 255。默认情况下,0等于黑色,255等于白色。要更改此设置,可以使用内置的opencv函数bitwise_not

img_reverted= cv2.bitwise_not(img)
Run Code Online (Sandbox Code Playgroud)

现在,我们可以使用以下方法缩放数组:

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 
Run Code Online (Sandbox Code Playgroud)