[英]Converting image to black and white and use it as array
我正在嘗試將彩色圖像轉換為黑白圖像。
原始圖像如下:
我有幾個問題。 第一:
import pylab as pl
import Image
im = Image.open('joconde.png')
pl.imshow(im)
pl.axis('off')
pl.show()
我得到這個:
為什么要旋轉? 那不是重點,但是我想知道為什么。
im_gray = im.convert('1')
pl.imshow(im_gray)
pl.show()
這是經過處理的黑白圖像:
現在一切看起來都正常了。 但是我需要將該圖像用作numpy數組,以便進行一些圖像處理。 我要做的就是:
import numpy as np
im_arr = np.array(im_gray)
pl.imshow(im_arr)
pl.axis('off')
pl.show()
但是我得到這個:
為什么會這樣呢? 我也嘗試過:
im_arr = np.array(im_gray, dtype='float')
要么:
im_arr = np.asarray(im_gray)
但是似乎沒有任何效果。 也許問題出在show
方法中,但我不知道。
由於原點問題,圖像被旋轉。
如果使用此代碼段,則圖像不會上下翻轉。
pl.imshow(im, origin='lower')
pl.show()
您也可以只使用im.show()
來顯示圖像。
現在,回到原來的問題。 我認為問題出在pylab無法處理雙層圖像這一事實。 您當然要使用灰度圖像,然后執行此操作
import pylab as pl
import matplotlib.cm as cm
import numpy as np
import Image
im = Image.open('your/image/path')
im_grey = im.convert('L') # convert the image to *greyscale*
im_array = np.array(im_grey)
pl.imshow(im_array, cmap=cm.Greys_r)
pl.show()
問題在於您將圖像轉換為numpy數組的方式。 如果您看一下這些函數的輸出是什么,這將變得很清楚
>> np.array(im_gray)
array([[False, False, False, ..., True, False, False],
[ True, True, True, ..., True, True, False],
[ True, True, True, ..., True, True, False],
...,
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False]], dtype=bool)
那是不對的。 pl.imshow
采用floats
uint8
或PIL
圖像數組,而不是布爾數組。 因此,您需要更明確地將其轉換為數組,並確保
cols,rows = im_gray.size
pixels = list(im_gray.getdata())
# an indexer into the flat list of pixels
# head ranges from 0 to len(pixels) with step cols
# tail ranges from cols to len(pixels) with step cols
head_tail = zip(range(0,len(pixels)+1,cols),range(cols,len(pixels)+1,cols))
im_data = np.ndarray(shape=(cols,rows), dtype=np.uint8)
# extract each row of pixels and save it to the numpy array
for i,(head,tail) in enumerate(head_tail):
im_data[i] = np.array(pixels[head:tail], dtype=np.uint8)
pl.imshow(im_data, cmap='bone')
最終的pl.imshow
需要您定義一個顏色圖。 'bone'
顏色圖是黑白的。 我假定將PIL
圖像傳遞到函數中以自動定義顏色圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.