我在 numpy.array 中有一个图像,我需要将所有行分成 4 个“相等”(忽略奇数)组和 4 组 cols。我试过这个:
for count in range(0, camera.shape[0], camera.shape[0] // 4):
pp.figure()
if count == 0:
pp.imshow(camera[0:camera.shape[0] // 4:, :], cmap='gray')
continue
pp.imshow(camera[count: count * 2:, :], cmap='gray')
# pp.imshow(camera[0:camera.shape[0] // 4:, :], cmap='gray')
pp.show()
结果: 但是这种方法在第一个循环和 begin:end:step 方面存在问题。一些提示?
我还制作了这张图片来说明我想要什么:
请您参考如下方法:
您可以将您的逻辑与 zip 函数一起使用,并动态地进行拆分::
def split(img, rows, cols):
'''
Split array in n rows and columns
Parameters
----------
img:
Arbitrary Numpy array
rows:
Number of rows to split the array
cols:
Number of cols to split the array
Usage
-----
>>> split(skimage.data.camera(), 4, 4)
Return
------
Python list containing the subsets
'''
cache = []
try:
img_r = img.shape[0]
img_c = img.shape[1]
except Exception as e:
raise Exception(
f'\nInform a \033[31mNumpy\033[37m array\n\n{str(e)}\n')
for c, n in zip(range(0, img_r + 1, img_r // rows), range(img_r // rows, img_r + 1, img_r // rows)):
for i, f in zip(range(0, img_c + 1, img_c // cols), range(img_c // cols, img_c + 1, img_r // cols)):
cache.append(img[c:n, i:f])
return cache
