Opencv 矩阵运算python API
ndarray 的加法
与c++中Mat加法直接将123+150截断为255的方式不同,ndarray的处理方式是对大于255的数对255求余数再减1
import numpy as np
src1 = np.array([[23, 123,90],[100, 250, 0]],np.uint8)#uint8 即 uchar
src2 = np.array([[125, 150,60],[100,10,40]],np.uint8)
dst = src1 + src2
print(dst)
[[148 17 150]
[200 4 40]]
两个不同类型的数据类型相加返回类型与数值范围大的数值类型相同
src3 = np.array([[125, 150,60],[100,10,40]],np.float32)
dst = src1 + src3
print(dst)
[[148. 273. 150.]
[200. 260. 40.]]
ndarray的减法
numpy的处理方式 (23 - 125)%255+1
dst = src1 - src2
print(dst)
[[154 229 30]
[ 0 240 216]]
ndarray的点乘
#使用“*”运算符
dst = src1 * src3
print(dst)
dst = np.multiply(src1, src3)
print(dst)
[[ 2875. 18450. 5400.]
[10000. 2500. 0.]]
[[ 2875. 18450. 5400.]
[10000. 2500. 0.]]
ndarray的点除
如果两个ndarray都为uint8分母为0时返回0,其他情况返回inf
dst = src2 / src1
print(dst)
dst = src3 / src1
print(dst)
[[5.43478261 1.2195122 0.66666667]
[1. 0.04 inf]]
[[5.4347825 1.2195122 0.6666667]
[1. 0.04 inf]]
E:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in true_divide
"""Entry point for launching an IPython kernel.
E:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: RuntimeWarning: divide by zero encountered in true_divide
This is separate from the ipykernel package so we can avoid doing imports until
ndarray的乘法
在ndarray中使用 * 或者multiply可以完成两个矩阵的点乘,而矩阵的乘法需要使用dot函数
src4 = np.array([[1,2,3],[4,5,6]],np.uint8)
src5 = np.array([[6,5],[4,3],[2,1]],np.uint8)
dst = np.dot(src4, src5)
print(dst)
[[20 14]
[56 41]]
两个不同的数据类型也可以相乘返回的类型为范围大的
src6 = np.array([[1,2,3],[4,5,6]],np.uint8)
src7 = np.array([[6,5],[4,3],[2,1]],np.float32)
dst = np.dot(src6, src7)
print(dst)
[[20. 14.]
[56. 41.]]
ndarray的指数运算与对数运算
src8 = np.array([[6,5],[4,3]],np.uint8)
dst = np.log(src8)
dst.dtype
print(dst)
[[1.792 1.609]
[1.387 1.099]]
src9 = np.array([[6,5],[4,3]],np.uint8)
dst = np.exp(src9)
print(dst)
[[403.5 148.4 ]
[ 54.6 20.08]]
ndarray的幂指数运算和开平方运算
src = np.array([[25,40],[20,100]],np.uint8)
dst = np.power(src,2)
print(dst.dtype)
print(dst)
dst = np.power(src,2.0)
print(dst)
print(dst.dtype)
uint8
[[113 64]
[144 16]]
[[ 625. 1600.]
[ 400. 10000.]]
float64