2017-09-24 164 views
2

我试图为一个字母图像创建一个位图,但是我没有获得所需的结果。我开始使用图像已经有几天了。我试图读取图像,创建一个numpy数组并将其保存在一个文件中。我写的代码波纹管:将图像转换为位图

import numpy as np 
from skimage import io 
from skimage.transform import resize 

image = io.imread(image_path, as_grey=True) 
image = resize(image, (28, 28), mode='nearest') 
array = np.array(image) 
np.savetxt("file.txt", array, fmt="%d") 

我想在这个环节波纹管使用的图片,如:

Letter "e"

我试图创建0和1组成的数组。 0代表白色像素,1代表黑色像素。然后,当我将结果保存在文件中时,我可以看到字母格式。

任何人都可以指导我如何得到这个结果吗?

谢谢。

回答

1

检查这一个:

from PIL import Image 
import numpy as np 

img = Image.open('road.jpg') 
ary = np.array(img) 

# Split the three channels 
r,g,b = np.split(ary,3,axis=2) 
r=r.reshape(-1) 
g=r.reshape(-1) 
b=r.reshape(-1) 

# Standard RGB to grayscale 
bitmap = list(map(lambda x: 0.299*x[0]+0.587*x[1]+0.114*x[2], 
zip(r,g,b))) 
bitmap = np.array(bitmap).reshape([ary.shape[0], ary.shape[1]]) 
bitmap = np.dot((bitmap > 128).astype(float),255) 
im = Image.fromarray(bitmap.astype(np.uint8)) 
im.save('road.bmp') 

该方案需要一个RGB图像,并将其转换以numpy的阵列。然后它将它分成3个矢量,每个通道一个。我使用颜色矢量来创建一个灰色矢量。之后,它与128个元素进行竞争,如果低于写入0(黑色),则其他元素为255.下一步是重塑并保存。

road.jpg road.bmp

+0

帮助很大。谢谢。如果我需要将所有位图大小调整为32x32,该怎么办?我怎么能这样做? –

+0

我想将图像大小调整为32x32或其他分辨率,而不会使其变形太多而失去其格式。我想要一个默认分辨率,所以我可以创建这些图像的数据集。 –

+0

很高兴解决。对不起,我没有这个答案。我自己正在使用张量流,而且我几乎没有使用opencv的经验。我不知道它是否值得您购买,但我建议您选择一个涵盖您的需求的库,坚持下去,如果遇到问题,请在stackoverflow中询问。玩得开心:) – prometeu

1

需要三个步骤才能完成。首先将原始图像转换为像素列表。其次将每个像素更改为黑色(0,0,0)或白色(255,255,255)。第三次将列表转换回图像并保存。

代码:

from PIL import Image 

threshold = 10 

# convert image to a list of pixels 
img = Image.open('letter.jpg') 
pixels = list(img.getdata()) 

# convert data list to contain only black or white 
newPixels = [] 
for pixel in pixels: 
    # if looks like black, convert to black 
    if pixel[0] <= threshold: 
     newPixel = (0, 0, 0) 
    # if looks like white, convert to white 
    else: 
     newPixel = (255, 255, 255) 
    newPixels.append(newPixel) 

# create a image and put data into it 
newImg = Image.new(img.mode, img.size) 
newImg.putdata(newPixels) 
newImg.save('new-letter.jpg') 

threshold是什么决定一个像素为黑色或白色,你可以看到它的代码。 50的阈值看起来像这样enter image description here,阈值30看起来像这样enter image description here,阈值10看起来像这样enter image description here,如果调整到5,输出开始失去像素:enter image description here