微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将二进制图像划分为像素数据的“块”

如何解决将二进制图像划分为像素数据的“块”

| 我正在使用Python和PIL作为将数据嵌入二进制图像的工作的一部分,并且需要分析像素组以确定要操纵的适当像素才能嵌入数据。需要将图像分成相等的“块”以准备分析的像素数据,但是我正努力提出一种合适的方法来进行此分析。我尝试过使用Python和numPy数组的技术,但没有成功。任何建议将不胜感激。 谢谢

解决方法

您需要使用
numpy
array
切片才能获得像素组。图像只是2D数组,因此可以使用
arr = numpy.array(Image.open(filename))
,然后对其进行切片。
#this code block from my fractal dimension finder
step = 2**a
for j in range(2**l):
    for i in range(2**l):
        block = arr[j * step:(j + 1) * step,i * step:(i + 1) * step]
,您可以使用鲜为人知的跨步技巧来创建由块构建的图像视图。它非常快,并且不需要占用任何额外的内存(示例有点冗长):
import numpy as np

#img = np.array(Image.open(filename),dtype=\'uint8\')

w,h = 5,4 # width,height of image
bw,bh = 2,3 # width,height of blocks

img = np.random.randint(2,size=(h,w)) # create a random binary image

# build a blocky view of the image data
sz = img.itemsize # size in bytes of the elements in img
shape = (h-bh+1,w-bw+1,bh,bw) # the shape of the new array: two indices for the blocks,# two indices for the content of each block
strides = (w*sz,sz,w*sz,sz) # information about how to map indices to image data
blocks = np.lib.stride_tricks.as_strided(img,shape=shape,strides=strides)

# now we can access the blocks
print img
[[1 1 0 0 0]
 [0 1 1 0 0]
 [0 0 1 0 1]
 [1 0 1 0 0]]

print blocks[0,0]
[[1 1]
 [0 1]
 [0 0]]

print blocks[1,2]
[[1 0]
 [1 0]
 [1 0]]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。