使用 Numpy 在 Python 中处理图像

Image handling in Python with Numpy

我们正在将网页的屏幕截图直接导入 Python 中的变量;然后使用以下代码生成一个 Numpy 数组:

要捕获的是 PNG 图像(注意 - 设备 url 具有嵌入式 cgi 来执行捕获工作):

response = requests.get(url.format(ip, device), auth=credentials)

捕获屏幕后,转换为名为图像的 Numpy 数组:

image = imread(BytesIO(response.content))

图片分析完成后,我们想FTP将捕获的PNG上传到服务器供日后参考。我们现在能找到的最佳解决方案是使用 imsave 在本地创建文件,然后 FTP 使用 storbinary 获取本地图像并将其放在服务器上。

是否可以FTPresponse.content;或者将 numpy 数组转换回 PNG(使用 imsave?)直接发送到服务器并跳过本地存储步骤?

更新

根据 MattDMo 评论,我们尝试了:

def ftp_artifact (ftp_ip, ftp_dir, tid, artifact_name, artifact_path, imgdata) :
   ftp = FTP(ftp_ip)
   ftp.login("autoftp","autoftp")
   ftp.mkd ("FTP/" + ftp_dir)
   ftp.cwd("FTP/" + ftp_dir)
   filepath = artifact_path
   filename = artifact_name
   f = BytesIO(imgdata)
   ftp.storbinary ('STOR ' + filename, f)
   ftp.quit()

其中 imgdata 是 io.imread 的结果。结果文件大 5 倍,而不是图像。 BytesIO 对象是我推测的 numpy 数组吗?

ftplib模块中,FTP.storbinary()方法将一个打开的文件对象作为它的第二个参数。由于您的 BytesIO 对象可以充当文件对象,因此您需要做的就是传递它 - 不需要服务器上的临时文件。

编辑

在没有看到您的完整代码的情况下,我怀疑发生的情况是您将 NumPy 数组传递给 storbinary(),而不是 BytesIO 对象。您还需要在上传前通过调用 bytesio_object.seek(0) 确保对象的读取指针位于开头。以下代码演示了如何执行所有操作:

from ftplib import FTP
from io import BytesIO
import requests

r = requests.get("http://example.com/foo.png")
png = BytesIO(r.content)

# do image analysis

png.seek(0)
ftp = FTP("ftp.server.com")
ftp.login(user="username", passwd="password")
# change to desired upload directory
ftp.storbinary("STOR " + file_name, png)
try:
    ftp.quit()
except:
    ftp.close()

进行了一些研究,但我们的学生发现了它:

def ftp_image_to(ftp_ip, ftp_dir, filename, data):
    ftp = FTP(ftp_ip)
    print("logging in")
    ftp.login('autoftp', 'autoftp')
    print("making dir")
    ftp.mkd('FTP/' + ftp_dir)
    ftp.cwd('FTP/' + ftp_dir)
    print("formatting image")
    bytes = BytesIO()
    plt.imsave(bytes, data, format='png')
    bytes.seek(0)
    print("storing binary")
    ftp.storbinary('STOR ' + filename, bytes)
    ftp.quit()

谢谢IH!