一、reshape
a = np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
print(a)
b = np.reshape(a,(12,1))
print(b)
print(a)
结果为
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]
[12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
所以,使用np.reshape(array,shape)不改变原始矩阵的shape,同时有返回值
a = np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
print(a)
b = a.reshape(12,1)
print(b)
print(a)
使用 a.reshape(shape)形式时,结果一样。
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]
[12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
二、resize
1.numpy中
a = np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
print(a)
c = a.resize(4,3)
print(c)
print(a)
结果为
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
None
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
使用a.resize(shape)形式,resize返回值为None,对原始矩阵进行修改
a = np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
print(a)
c = np.resize(a,(4,3))
print(c)
print(a)
结果为
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
使用np.resize(array,shape)的形式,同np.reshape一样,有返回值,不改变原始矩阵的shape
2.opencv
a = np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
print(a)
c = cv2.resize(a,(4,3))
print(c)
print(a)
结果为
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
这里有一些问题,
一个是,cv2的resize先从x轴,再y轴,即先列后行(先高后宽),所以resize(4,3)结果是三行四列。
附上cv的文档
resize
Resizes an image.
C++: void resize(InputArray src, OutputArray dst, Size dsize, double fx=0, double fy=0, int interpolation=INTER_LINEAR )¶
Python: cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]]) → dst
C: void cvResize(const CvArr* src, CvArr* dst, int interpolation=CV_INTER_LINEAR )
Python: cv.Resize(src, dst, interpolation=CV_INTER_LINEAR) → None
Parameters:
src – input image.
dst – output image; it has the size dsize (when it is non-zero) or the size computed from src.size(), fx, and fy; the type of dst is the same as of src.
dsize –
output image size; if it equals zero, it is computed as:
\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}
Either dsize or both fx and fy must be non-zero.
---------------------
原文:https://blog.youkuaiyun.com/loovelj/article/details/81097614
在resize改为(3,4)后,报错如下:
error: (-215:Assertion failed) func != 0 in function 'cv::hal::resize'
错误原因还未研究透彻,暂时搁置。
将代码改为如下形式,则不会报错:
a = np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]],dtype=float
print(a)
c = cv2.resize(a,(3,4))
print(c)
print(a)
结果为:
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
[[ 1.16666667 2.5 3.83333333]
[ 3.66666667 5. 6.33333333]
[ 6.66666667 8. 9.33333333]
[ 9.16666667 10.5 11.83333333]]
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
同时可以看到,矩阵被改为4x3列