python - 值错误 : total size of new array must be unchanged

标签 python opencv image-processing

我正在尝试执行此 URL 中的代码.但是,我开始收到此错误:

des = np.array(des,np.float32).reshape((1,128))
ValueError: total size of new array must be unchanged

虽然我没有做任何重大改变。但我会粘贴我所做的:

import scipy as sp
import numpy as np
import cv2

# Load the images
img =cv2.imread("image1.png")

# Convert them to grayscale
imgg =cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# SURF extraction
surf = cv2.FeatureDetector_create("SURF")
surfDescriptorExtractor = cv2.DescriptorExtractor_create("SURF")
kp = surf.detect(imgg)
kp, descritors = surfDescriptorExtractor.compute(imgg,kp)

# Setting up samples and responses for kNN
samples = np.array(descritors)
responses = np.arange(len(kp),dtype = np.float32)

# kNN training
knn = cv2.KNearest()
knn.train(samples,responses)

modelImages = ["image2.png"]

for modelImage in modelImages:

    # Now loading a template image and searching for similar keypoints
    template = cv2.imread(modelImage)
    templateg= cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)
    keys = surf.detect(templateg)

    keys,desc = surfDescriptorExtractor.compute(templateg, keys)

    for h,des in enumerate(desc):
        des = np.array(des,np.float32).reshape((1,128))

        retval, results, neigh_resp, dists = knn.find_nearest(des,1)
        res,dist =  int(results[0][0]),dists[0][0]

        if dist<0.1: # draw matched keypoints in red color
            color = (0,0,255)

        else:  # draw unmatched in blue color
            #print dist
            color = (255,0,0)

        #Draw matched key points on original image
        x,y = kp[res].pt
        center = (int(x),int(y))
        cv2.circle(img,center,2,color,-1)

        #Draw matched key points on template image
        x,y = keys[h].pt
        center = (int(x),int(y))
        cv2.circle(template,center,2,color,-1)



    cv2.imshow('img',img)
    cv2.imshow('tm',template)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

非常感谢对此的任何帮助。

最佳答案

我遇到了同样的问题。我发现我改变了数据长度。 reshape 参数的乘积应等于您要更改的数组的长度。 在你的情况下:

des = np.array(des,np.float32).reshape(1, len(des))

关于python - 值错误 : total size of new array must be unchanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26295491/

相关文章:

python - python是否支持基本多语言平面之外的unicode?

c++ - 使用 CUDA 7.0/VS2012 C++/CLI/OpenCV 的多线程 CPU 到 GPU

opencv - 计算图片与其草图的相似度

java - 如何在Java中调整.bmp图像的大小?

python - 使 isort 将来自 Django 应用程序的导入识别为第一方导入

python - Django 模板中带空格的字典键

python - 如何检测图表区域并从研究论文的图像中提取(裁剪)它

c++ - 需要找到一种使用 OpenCV 在二维图像中检测息肉的方法

python - 游戏图像识别(识别《Flappy Bird》中的得分或游戏结束)

Python的字典列表值的hasattr总是返回false?