[英]How to save a plot as a black and white png file in Python
我正在嘗試將matplotlib
plot 保存為黑白png
文件,然后能夠將圖像作為numpy
數組打開。 問題是我得到的array
由每個像素的 4 個值組成,而不是只有 1 個(因為我的圖像是黑白的)
這是我的代碼:
import matplotlib.pyplot as plt
import numpy as np
# To generate my image
text = 'Text'
plt.text(0.4, 0.4, text)
plt.axis('off')
plt.savefig(f'Image.png', dpi=100)
但是,當我使用此代碼將其作為array
打開時:
import numpy as np
import matplotlib.image as ima
image = ima.imread(f'Image.png')
print(image)
我得到這樣的東西:
array([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
...,
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
...,
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
...,
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
...,
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]], dtype=float32)
而不是這樣的:
array([[1, 1, 1, ..., 1, 1, 1],
[1, 1, 1, ..., 1, 1, 1],
...,
[1, 1, 1, ..., 0, 0, 0, ..., 1, 1, 1],
...,
[1, 1, 1, ..., 1, 1, 1], dtype=float32)
我已經考慮過通過創建一個新數組來使用for loop
手動完成它,該數組采用每個像素的第一個值(由 4 個值組成),但它可能不是最佳的......
因此,有沒有辦法正確地做到這一點?
這里有幾個問題:
plt.save fig()
在 RGBA 色彩空間中保存,即 3 個 RGB 通道和一個 alpha/透明通道,因此你得到 4 個通道您可以像當前一樣保存為 PNG,然后使用OpenCV (或PIL或其他)將圖像讀取為灰度圖像,以獲取 0..255 范圍內的單個通道,如下所示:
import numpy as np
import cv2
# Load a single channel greyscale image
na = cv2.imread('Image.png', cv2.IMREAD_GRAYSCALE)
print(na.shape) # prints (480,640)
print(im.max()) # prints 255
如果你不想引入OpenCV ,你可以寫成raw
格式,即 8 位數據的每個像素 4 個樣本 (RGBA)。 那看起來像這樣:
...
...your existing code
...
plt.savefig(f'Image.raw', dpi=100)
# Now read back into Numpy array
na = np.fromfile('Image.raw', dtype=np.uint8).reshape((480,640,4))
# Choose first channel as they should be all the same
im = na[..., 0]
請注意,無需寫入磁盤來保存和讀取文件 - 您可以寫入 memory 緩沖區:
from io import BytesIO
# Get a memory buffer
buffer = BytesIO()
# Save as PNG into memory buffer
plt.savefig(buffer, dpi=100)
您現在在 memory 中有一個 PNG 編碼的圖像:
print(buffer.getvalue()[:20])
Output:
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x02\x80'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.