今天继续做一个物理外挂小项目,记录用到的有趣的numpy function
使用常用库的build-in func的好处:弥补Py大循环性能极差的弱点,常用库基于SSE,AVX指令集做SIMD等优化,性能提升极大;

1.基于阈值仅使用一个表达式来对numpy array操作
np.random.seed(0)
np.set_printoptions(precision=3)
a = np.random.rand(4, 4)
threshold, upper, lower = 0.5, 1, 0
a[a>threshold] = upper
a[a<=threshold] = lower
2.nonzero函数返回非零元素的目录
A = np.random.rand(4, 4)
x = A.nonzero()
3.numpy.where()

满足条件(condition),输出x,不满足输出y

>>> aa = np.arange(10)
>>> np.where(aa,1,-1)
array([-1,  1,  1,  1,  1,  1,  1,  1,  1,  1])  # 0为False,所以第一个输出-1
>>> np.where(aa > 5,1,-1)
array([-1, -1, -1, -1, -1, -1,  1,  1,  1,  1])

>>> np.where([[True,False], [True,True]],    # 官网上的例子
             [[1,2], [3,4]],
             [[9,8], [7,6]])
array([[1, 8],
       [3, 4]])
4.cornerHarris()
# function prototype
dst =cv.cornerHarris( src, blockSize, ksize, k[, dst[, borderType]] )
import numpy as np
import cv2 as cv
filename = 'chessboard.png'
img = cv.imread(filename)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv.imshow('dst',img)
if cv.waitKey(0) & 0xff == 27:
    cv.destroyAllWindows()

more detail:official docs

最后修改日期: 2019年1月31日

作者

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。