遇到这么个需求:把图片按照定义的patchsize切块,然后按照z轴顺序叠放小块,如下图(仅考虑灰度图像)
图片im,设size为(h,w),patchsize为(ph,pw),则处理后大小(为简化描述,假设可以整除)为(ph,pw,w*h/ph/pw)。
为简化描述,后面用h=300,w=300,ph=100,pw=100 为例,即处理后d=9。
numpy.reshape 的文档:点击打开链接
特别注意第三个参数 order,其默认取值为 order=‘c',表示最后一个维度的元素在reshape时优先重排位置。而order=‘f'时则相反,第一个维度的元素优先重排位置。
例子如下,得到的im2就是这么一个tensor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import cv2 import numpy as np im = cv2.imread( 'animal007.jpg' ,cv2.imread_grayscale) h = 300 w = 300 patchsize = 100 d = h * w / patchsize / patchsize print d #crop the image to h x w im = np.array(im[: h ,: w ]) #this gets wrong answer im_wrong1 = im.reshape((patchsize,patchsize, - 1 )) im_wrong7 = im.reshape((patchsize,patchsize, - 1 ),order = 'f' ) im_wrong2 = im.reshape(( h ,patchsize, - 1 )).reshape((patchsize,patchsize, - 1 )) im_wrong3 = im.reshape((patchsize, w , - 1 )).reshape((patchsize,patchsize, - 1 )) im_wrong4 = im.reshape(( h ,patchsize, - 1 ),order = 'f' ).reshape((patchsize,patchsize, - 1 )) im_wrong5 = im.reshape(( h ,patchsize, - 1 ),order = 'f' ).reshape((patchsize,patchsize, - 1 ),order = 'f' ) im_wrong6 = im.reshape((patchsize, w , - 1 ),order = 'f' ).reshape((patchsize,patchsize, - 1 ),order = 'f' ) #this only works for h=w, i dont know why im2 = im.reshape((patchsize, w , - 1 ),order = 'f' ).reshape((patchsize,patchsize, - 1 )) im2_0 = im2[:,:,no] cv2.imwrite( 'im2_0.jpg' ,im2_0) no = 4 ; imw = im_wrong1[:,:,no] cv2.imwrite( 'imw1_0.jpg' ,imw) imw = im_wrong2[:,:,no] cv2.imwrite( 'imw2_0.jpg' ,imw) imw = im_wrong3[:,:,no] cv2.imwrite( 'imw3_0.jpg' ,imw) imw = im_wrong4[:,:,no] cv2.imwrite( 'imw4_0.jpg' ,imw) imw = im_wrong5[:,:,no] cv2.imwrite( 'imw5_0.jpg' ,imw) imw = im_wrong6[:,:,no] cv2.imwrite( 'imw6_0.jpg' ,imw) imw = im_wrong7[:,:,no] cv2.imwrite( 'imw7_0.jpg' ,imw) |
以上这篇在python2.7中用numpy.reshape 对图像进行切割的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u014722627/article/details/55259617