import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('timg.jpg') #原图为彩色图,可将第二个参数变为0,为灰度图
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 输入图像必须是float32, 最后一个参数[0.04,0.06]
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04) #输入图像的数据类型必须为float32,
dst = cv2.dilate(dst,None) #放大标记角点,利于显示
img[dst>0.01*dst.max()]=[0,0,255]#最佳值的阈值选用0.01*dst.max(),可能会根据图像而有所不同。
cv2.imshow('dst',img)
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
cv2.imwrite('test.png',img)
Shi-Tomasi角点检测
import numpy as np
import cv2
img = cv2.imread('timg.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray,25,0.01,10)
corners = np.int0(corners)
for i in corners:
x,y = i.ravel()
cv2.circle(img,(x,y),3,255,-1)
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.imwrite('test.png',img)
// 常用如下参数:
void cv::goodFeaturesToTrack(image,corner,
25, // 最多检测到的角点数
0.01, // 阈值系数
10); // 角点间的最小距离
2.特征匹配
KNN
import cv2
from matplotlib import pyplot as plt
img1 = cv2.imread('1.png', 0)
img2 = cv2.imread('2.png', 0)
# 使用ORB特征检测器和描述符,计算关键点和描述符
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
bf = cv2.BFMatcher(normType=cv2.NORM_HAMMING, crossCheck=True)
# knnMatch 函数参数k是返回符合匹配的个数,暴力匹配match只返回最佳匹配结果。
matches = bf.knnMatch(des1,des2,k=1)
# 使用plt将两个图像的第一个匹配结果显示出来
# 若使用knnMatch进行匹配,则需要使用drawMatchesKnn函数将结果显示
img3 = cv2.drawMatchesKnn(img1=img1,keypoints1=kp1,
img2=img2,keypoints2=kp2,
matches1to2=matches[:40],
outImg=img2, flags=2)
plt.imshow(img3)
plt.show()
ORB
import cv2
from matplotlib import pyplot as plt
def match_ORB():
img1 = cv2.imread('1.png',0)
img2 = cv2.imread('2.png',0)
# 使用ORB特征检测器和描述符,计算关键点和描述符
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
bf = cv2.BFMatcher(normType=cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1,des2)
matches = sorted(matches, key = lambda x:x.distance)
img3 = cv2.drawMatches(img1=img1,keypoints1=kp1,
img2=img2,keypoints2=kp2,
matches1to2=matches,
outImg=img2, flags=2)
return img3
if __name__ == '__main__':
img3 = match_ORB()
plt.imshow(img3)
plt.show()
3. 图片拼接
import numpy as np
import cv2
from cv2 import Stitcher
if __name__ == "__main__":
img1 = cv2.imread('1.jpg')
img2 = cv2.imread('2.jpg')
stitcher = cv2.Stitcher.create(cv2.Stitcher_PANORAMA)
(_result, pano) = stitcher.stitch((img1, img2))
cv2.imshow('pano',pano)
cv2.imwrite('test.jpg',pano)
cv2.waitKey(0)
4.图像插值
相关代码:https://blog.csdn.net/u010096025/article/details/53780623?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
效果:
原图
双三次
双线性
最近邻
部分代码参考网络资源,侵删!