简体   繁体   English

将 ndarray 转换为 Base64

[英]Converting ndarray to Base64

A user uploads an image, if that user doesn't have another image to upload then that image is saved.用户上传图像,如果该用户没有要上传的其他图像,则保存该图像。 We then take that image, slice it in two halves.然后我们拍摄该图像,将其切成两半。 The first half gets saved again.上半场再次得救。 As for the second image, we need to convert it into a Base64 Image.至于第二张图像,我们需要将其转换为 Base64 图像。 However, for some reason I'm getting this error: ValueError: ndarray is not C-contiguous但是,由于某种原因,我收到此错误: ValueError: ndarray is not C-contiguous

img = q.choice_set.all()[0].img
reader = misc.imread(img)
height, width, _ = reader.shape
with_cutoff = width // 2
s1 = reader[:, :with_cutoff]
s2 = reader[:, with_cutoff:]
misc.imsave(settings.MEDIA_ROOT + "/" + img.name, s2)
validated_data["choiceimage"] = base64.b64encode(s2)

When I save this in the database, I get an error.当我将其保存在数据库中时,出现错误。 What am I doing wrong?我究竟做错了什么? How can I decode the numpy array into base64?如何将 numpy 数组解码为 base64?

If you take a 2D array and extract the left or right half, it will no longer be contiguous in memory - there will be gaps between the rows.如果您采用二维数组并提取左半部分或右半部分,它将在内存中不再连续 - 行之间会有间隙。

x = np.arange(6).reshape(2,3)

gives x :给出x

array([[0, 1, 2],
       [3, 4, 5]])

If we extract the central column into y :如果我们将中心列提取到y

y = x[:,1:2]

gives y :y

array([[1],
       [4]])

but if we check if it is contiguous in memory:但是如果我们检查它在内存中是否是连续的:

y.flags['C_CONTIGUOUS']

gives:给出:

False

The solution is to extract the column into a contiguous array:解决方案是将列提取到连续数组中:

y = np.ascontiguousarray(x[:,1:2])
y.flags['C_CONTIGUOUS']

gives:给出:

True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM