2017-09-24 163 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