【问题标题】:TypeError: can't convert type 'ndarray' to numerator/denominatorTypeError:无法将类型“ndarray”转换为分子/分母
【发布时间】:2021-01-03 02:36:03
【问题描述】:

Error which I am getting 这是我的代码。我无法理解这个错误。我已经尝试了很多但没有得到正确的解决方案。请帮助我知道错误是什么。

import numpy as np
import cv2
from skimage.feature import local_binary_pattern
import statistics 
from os import read
from google.colab.patches import cv2_imshow

cap = cv2.VideoCapture('/content/4.forged4.avi')

countF = cap.get(cv2.CAP_PROP_FPS) # calculate no of frames per sec

while True:
   ret, frame = cap.read()
   if ret:
     gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     gray = np.array(gray_img).astype(int)
     frames.append(gray)
     #cv2_imshow(gray_img) 
     radius = 3

     p = 8 * radius
     lbp =  local_binary_pattern(gray_img,p, radius, method = 'uniform') 
     print(lbp)
     val =  statistics.stdev(lbp) # caluculated standard deviation
     print(val)
     if val == 0:
       print("Authenticated")
     else:
       print("Forgery Detected!")

【问题讨论】:

标签: python numpy


【解决方案1】:

statistics.stdev 期望具有至少两个值的实数的可迭代(例如列表)作为参数。您将不满足该要求的变量 lbp 传递给它(它是列表列表)。如果文档不是很清楚,您可以运行简单的实验来查看函数的行为方式。这是例如我做了什么:

$ python3
>>> import statistics
>>> help(statistics.stdev)
Help on function stdev in module statistics:

stdev(data, xbar=None)
    Return the square root of the sample variance.

    See ``variance`` for arguments and other details.
    ...
>>> help(statistics.variance)
Help on function variance in module statistics:

variance(data, xbar=None)
    Return the sample variance of data.

    data should be an iterable of Real-valued numbers, with at least two
    values.
    ....
>>> l = [[1.0 ,2.0, 3.0], [4.0, 5.0, 6.0]]
>>> statistics.stdev(l)
Traceback (most recent call last):
...
TypeError: can't convert type 'list' to numerator/denominator
>>> l = [1.0 ,2.0, 3.0]
>>> statistics.stdev(l)
1.0
>>> 

如您所见,将数字列表传递给 stdev 会产生您得到的错误,而传递数字列表则可以正常工作。

这个故事的寓意是,上面两行计算的本地二进制模式lbp 不是传递给stdev 的正确类型。

现在,这就是 python 程序失败的原因,但其根本原因很可能是您对应该做什么感到困惑。 如果计算lbp 中条目的标准差是有意义的(如果我不能为你回答,那就大了),那么你可以尝试扁平化lbp,这是一个列表在将列表传递给 stdev 之前,将列表缩减为单个列表。但这样做有意义吗?只有你能回答这个问题,而且只有你理解了你要解决的问题。

【讨论】:

  • 我想要视频中的伪造帧。我怎样才能使用它?
  • 我不知道您要做什么或如何做到:正如我所说,只有您可以回答这个问题。我所做的只是试图回答你关于你得到的错误以及它来自哪里的问题。
【解决方案2】:

@rohit-sharma,在statistics 模块中使用之前,您必须先展平数据。

假设lbp变量是一个ndarray:

改变:

     val =  statistics.stdev(lbp) # caluculated standard deviation

到:

     val =  statistics.stdev(lbp.flatten()) # caluculated standard deviation

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2021-04-13
    相关资源
    最近更新 更多