PYTHON3.6以上版本如PYTHON3.8安装SIFT
基于conda虚拟环境解决高版本opencv不支持SIFT特征算法的问题。
文章目录
前言
通过在高版本python环境下,安装虚拟环境,使用sift特征算法,进行大图找小图。
一、 问题描述
由于已安装anaconda,python版本为3.8,基于某些原因SIFT算法在高版本OPENCV中已取消,按其他文章介绍,到https://pypi.tuna.tsinghua.edu.cn/simple/opencv-python/
及
https://pypi.tuna.tsinghua.edu.cn/simple/opencv-contrib-python/
下载opencv_python-3.4.2.16 低版本安装文件手动安装。
在Lib\site-packages安装opencv_python-3.4.2.16-cp36-cp36m-win_amd64.whl 时提示Could not find a version that satisfies the requirement python-OpenCV. 问题原因是安装文件最高只支持CP36=PYTHON3.6,因此需安装虚拟环境,再装低版本OPENCV
二、步骤
1.安装虚拟环境
cmd 下 运行:
conda create -n your_env_name python=3.6
2.安装完成后激活环境
conda activate your_env_name
3.安装下载好的opencv及contribute
pip install opencv_python-3.4.2.16-cp36-cp36m-win_amd64.whl
pip install opencv_contrib_python-3.4.2.16-cp37-cp37m-win_amd64.whl
4.调用示例
代码如下(示例):
import io
from PIL import Image, ImageTk
import tkinter as tk
import cv2
import numpy as np
MIN_MATCH_COUNT = 4
img1 = cv2.imread("D:/OCR/mine.png")
img2 = cv2.imread("D:/OCR/TRAIN.jpg")
g1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
g2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
match = cv2.FlannBasedMatcher(dict(algorithm =2, trees =1), {})
kp1, de1 = sift.detectAndCompute(g1,None)
kp2, de2 = sift.detectAndCompute(g2,None)
m = match.knnMatch(de1, de2, 2)
m = sorted(m,key = lambda x:x[0].distance)
ok = [m1 for (m1, m2) in m if m1.distance < 0.7 * m2.distance]
med = cv2.drawMatches(img1, kp1, img2, kp2, ok, None)
cv2.imwrite("D:/OCR/b.jpg", med)
#
# cv2.imshow("0", med)
# cv2.waitKey()
# cv2.destroyAllWindows()
def resize(w, h, w_box, h_box, pil_image):
f1 = 1.0 * w_box / w # 1.0 forces float division in Python2
f2 = 1.0 * h_box / h
factor = min([f1, f2])
width = int(w * factor)
height = int(h * factor)
return pil_image.resize((width, height), Image.ANTIALIAS)
root = tk.Tk()
# size of image display box you want
# 期望图像显示的大小
w_box = 800
h_box = 1000
# 以一个PIL图像对象打开
pil_image = Image.open(r'D:/OCR/b.jpg')
# get the size of the image
# 获取图像的原始大小
w, h = pil_image.size
# resize the image so it retains its aspect ration
# but fits into the specified display box
# 缩放图像让它保持比例,同时限制在一个矩形框范围内
pil_image_resized = resize(w, h, w_box, h_box, pil_image)
# convert PIL image object to Tkinter PhotoImage object
# 把PIL图像对象转变为Tkinter的PhotoImage对象
tk_image = ImageTk.PhotoImage(pil_image_resized)
# put the image on a widget the size of the specified display box
# Label: 这个小工具,就是个显示框,小窗口,把图像大小显示到指定的显示框
label = tk.Label(root, image=tk_image, width=w_box, height=h_box)
# padx,pady是图像与窗口边缘的距离
label.pack(padx=5, pady=5)
root.mainloop()
相关参数说明及原理参考 https://blog.youkuaiyun.com/codedoctor/article/details/78998946
总结及注意事项
注意安装并激活新环境后,原3.8的类都需重新安装,需要在cmd的窗口下,显示((your_env_name) C:\Users\XXX>的环境下重新安装。另外新的Lib\site-packages文件夹默认在.conda\envs\your_env_name\Lib\site-packages目录下。
本文档详细介绍了如何在Python 3.8环境下,通过创建conda虚拟环境来解决高版本OpenCV不支持SIFT特征算法的问题。首先,需要从指定网址下载opencv_python的低版本whl文件,然后创建并激活虚拟环境,最后在该环境中安装低版本OpenCV及其贡献库,并提供调用示例。
2977





