Cv2在尝试比较2个图像时拒绝使用imread和TM_CCOEFF_NORMED(这是在pycharm,python 3.10.1中)

lqfhib0f  于 2023-05-17  发布在  PyCharm
关注(0)|答案(1)|浏览(218)

我试图使一个游戏,用户提交和图像,然后图像得到比较,以一个硬编码的模板。如果图像足够接近,则用户获胜。我大约3个月前编写了这段代码,当时它运行得很完美,但现在它只是拒绝运行。我一直收到这两个警告:Cannot find reference 'imread' in '__init__.py'Cannot find reference 'TM_CCOEFF_NORMED' in '__init__.py'下面是我的代码:

from tkinter import *
from mainwin import level
import tkinter as tk
from PIL import Image, ImageTk
import cv2
from tkinter import filedialog
import numpy as np

template = "D:\Imagechecks\c12.png"
# ^ hardcoded in ^

root = tk.Tk()
# makes a window for the file selection
root.title("Image Selector")

# Open file dialog to select image
file_path = filedialog.askopenfilename()

# Open image using Pillow
image = Image.open(file_path)

# Start Tkinter event loop

img = cv2.imread(image)
#           ^^the problem is pointing here
temp = cv2.imread(template)
#           ^^here
resolution = cv2.matchTemplate(img, temp, cv2.TM_CCOEFF_NORMED)
#                                                 ^^ and here.
threshold = .6
loc = np.where(resolution >= threshold)
print(resolution)
if len(loc[0]) == 0:
    labl_results = Label(root, text="LEVEL FAILED YOU LOOSER!").grid(row=12, column=0, columnspan=2)
    print("fail")
labl_results = Label(root, text="CONGRANTS. YOU DONE IT! ").grid(row=12, column=0, columnspan=2)
print("pass")
root.mainloop()

当我试图修复它时,代码给了我一个不同的错误:TypeError: Can't convert object to 'str' for 'filename'任何帮助将不胜感激
我试过:

  • 重新安装pycharm
  • 重新安装Python 3.10.1
  • 创建新文件并复制粘贴代码
  • 重新安装所有软件包
  • 使用cv2的白色版本
  • 在朋友的电脑上运行这些方法都不管用,他们都给出了同样的答案:imread和TM_CCOEFF出现问题...
bhmjp9jg

bhmjp9jg1#

imageGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
templateGray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)

resolution = cv2.matchTemplate(imageGray, templateGray, cv2.TM_CCOEFF_NORMED)

result = cv2.matchTemplate(imageGray, templateGray,
    cv2.TM_CCOEFF_NORMED)

更改此:

if len(loc[0]) == 0:
    labl_results = Label(root, text="LEVEL FAILED YOU LOOSER!").grid(row=12, column=0, columnspan=2)
    print("fail")
labl_results = Label(root, text="CONGRANTS. YOU DONE IT! ").grid(row=12, column=0, columnspan=2)
print("pass")

致:

if len(loc[0]) == 0:
    results = "LEVEL FAILED YOU LOOSER!" 
    print("fail")
else:
    results = "CONGRANTS. YOU DONE IT! "

labl_results = Label(root, text=result)
labl_results.grid(row=12, column=0, columnspan=2)

相关问题