如何从绘图中获取uint8类型的图像(Matplotlib)?

时间:2017-11-23 11:21:46

标签: python matplotlib

考虑以下代码:

extension Optional where Wrapped == String {
    func isEmailValid() -> Bool{
        guard let email = self else { return false }
        let emailPattern = "[A-Za-z-0-9.-_]+@[A-Za-z0-9]+\\.[A-Za-z]{2,3}"
        do{
            let regex = try NSRegularExpression(pattern: emailPattern, options: .caseInsensitive)
            let foundPatters = regex.numberOfMatches(in: email, options: .anchored, range: NSRange(location: 0, length: email.count))
            if foundPatters > 0 {
                return true
            }
        }catch{
            //error
        }
        return false
    }
}

所以我遇到的问题是,它会在文本“Test”上保存。但是假设我有一个情节,“AxesImages”matplotlib准确,我怎样才能转换图像而不是文本?我试图用 ax.imshow(axesImage)更改 ax.text(...),但它抛出并出错。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以将图像保存到文件中,然后使用PIL将文件加载到数组中:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.text(0.0,0.0,"Test", fontsize=45)
ax.axis('off')
ax.imshow(np.random.random((3,3)))
filename = '/tmp/out.png'
fig.savefig(filename)
img = Image.open(filename).convert('RGB')
arr = np.asarray(img)
img.show()

enter image description here

如果您想避免磁盘I / O,可以save the image to a BytesIO object instead

import io
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.text(0.0,0.0,"Test", fontsize=45)
ax.axis('off')
ax.imshow(np.random.random((3,3)))

with io.BytesIO() as memf:
    fig.savefig(memf, format='PNG')
    memf.seek(0)
    img = Image.open(memf)
    arr = np.asarray(img)
    img.show()