将图像转换为二进制数据

时间:2018-10-29 15:17:25

标签: python-2.7 image-processing

我想将灰度图像转换为二进制数据字符串。 我成功地做到了,但是结果定义为none而不是string,这意味着我无法检查长度。有什么建议可以解决这个问题,或者为此想法使用其他代码?谢谢。

这是我写的代码:

def pass_image(image_url):

    str = base64.b64encode(requests.get(image_url).content)

    print(str)
    print "".join(format(ord(x), "b") for x in decodestring(str))

1 个答案:

答案 0 :(得分:0)

我认为问题正在发生,因为您正在命名变量str。这是python类中用于字符串的名称,因此从本质上讲,您正在用变量覆盖字符串类定义,这意味着您将无法再使用它及其功能(例如len)

我能够通过以下更改来运行此代码,请尝试一下。我并不完全了解您的目标,但希望能有所帮助。另外,如果要在其他函数中使用它,请确保返回创建的对象

import base64
import requests

my_url = '...' # your url here

def pass_image(image_url):
    output = base64.b64encode(requests.get(image_url).content)
    bin = "".join(format(ord(x), "b") for x in base64.decodestring(output))
    return bin # or you could print it

len(pass_image(my_url)) # for the url I used, I got length of 387244

希望这会有所帮助!祝你好运。