gpt4 book ai didi

python - 简单数字识别中的OpenCV Python错误

转载 作者:行者123 更新时间:2023-12-02 17:11:53 25 4
gpt4 key购买 nike

import cv2
import numpy as np
####### training part ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
model = cv2.KNearest()
model.train(samples,responses)
############################# testing part #########################
im = cv2.imread('/home/manoj/Pictures/Untitled-1.jpg')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
roismall = roismall.reshape((1,100))
roismall = np.float32(roismall)
retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
string = str(int((results[0][0])))
cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

我将这个python代码与 Opencv一起用于字符识别,但是在运行代码时遇到此错误。

AttributeError: 'module' object has no attribute 'KNearest'

最佳答案

由于新的OpenCV版本,您需要更换

model = cv2.KNearest()

通过:
model = cv2.ml.KNearest_create()

此外,该行:
model.train(samples,responses)

也将引发错误,这应该解决它:
model.train(samples,cv2.ml.ROW_SAMPLE,responses) # Might be adapted

希望这会有所帮助。

关于python - 简单数字识别中的OpenCV Python错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35264144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com