numpy “TypeError:'NoneType'对象不是可订阅的

mrphzbgm  于 2023-05-17  发布在  其他
关注(0)|答案(3)|浏览(155)

我试图添加一些功能,我从https://raw.githubusercontent.com/vipul-sharma20/gesture-opencv/master/gesture.py,我可以捕获任何我需要的手掌,并将其保存在文件夹中的代码,在第一次尝试它的成功,但第二次是失败说:

Traceback (most recent call last):
File "home/pi/Downloads/palmdetect.py", line 97, in<module>
    camera_capture = get_image()
File "home/pi/Downloads/palmdetect.py", line 11, in get_image
    crop_image = img[100:450, 100:450]
TypeError: 'NoneType' object is not subscriptable

palmdetect.py中的代码:

import cv2
import numpy as np
import math

cap = cv2.VideoCapture(0)

def get_image():
    # read image
    ret, img = cap.read()
    # get hand data from the rectangle sub window on the screen
    cv2.rectangle(img, (300, 300), (100, 100), (0, 255, 0), 0)
    crop_img = img[100:300, 100:300]

    # convert to grayscale
    grey = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)

    # applying gaussian blur
    value = (35, 35)
    blurred = cv2.GaussianBlur(grey, value, 0)

    # thresholdin: Otsu's Binarization method
    _, thresh1 = cv2.threshold(blurred, 127, 255,
                               cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

    # show thresholded image
    cv2.imshow('Thresholded', thresh1)

    # check OpenCV version to avoid unpacking error
    (version, _, _) = cv2.__version__.split('.')

    if version == '3':
        image, contours, hierarchy = cv2.findContours(
            thresh1.copy(),
            cv2.RETR_TREE,
            cv2.CHAIN_APPROX_NONE
        )
    elif version == '2':
        contours, hierarchy = cv2.findContours(
            thresh1.copy(),
            cv2.RETR_TREE,
            cv2.CHAIN_APPROX_NONE
        )

    # find contour with max area
    cnt = max(contours, key=lambda x: cv2.contourArea(x))

    # create bounding rectangle around the contour (can skip below two lines)
    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(crop_img, (x, y), (x+w, y+h), (0, 0, 255), 0)

    # finding convex hull
    hull = cv2.convexHull(cnt)

    # drawing contours
    drawing = np.zeros(crop_img.shape, np.uint8)
    cv2.drawContours(drawing, [cnt], 0, (0, 255, 0), 0)
    cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 0)

    # finding convex hull
    hull = cv2.convexHull(cnt, returnPoints=False)

    # finding convexity defects
    defects = cv2.convexityDefects(cnt, hull)
    count_defects = 0
    cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3)

    # applying Cosine Rule to find angle for all defects (between fingers)
    # with angle > 90 degrees and ignore defects
    for i in range(defects.shape[0]):
        s, e, f, d = defects[i, 0]

        start = tuple(cnt[s][0])
        end = tuple(cnt[e][0])
        far = tuple(cnt[f][0])

        # find length of all sides of triangle
        a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2)
        b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2)
        c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2)

        # apply cosine rule here
        angle = math.acos((b**2 + c**2 - a**2)/(2*b*c)) * 57

        # ignore angles > 90 and highlight rest with red dots
        if angle <= 90:
            count_defects += 1
            cv2.circle(crop_img, far, 1, [0, 0, 255], -1)
        # dist = cv2.pointPolygonTest(cnt,far,True)

        # draw a line from start to end i.e. the convex points (finger tips)
        # (can skip this part)
        cv2.line(crop_img, start, end, [0, 255,  0], 2)
        # cv2.circle(crop_img,far,5,[0,0,255],-1)

    # show appropriate images in windows
    cv2.imshow('Gesture', img)
    all_img = np.hstack((drawing, crop_img))

    return img

temp = get_image()
print("Taking Image...")

camera_capture = get_image()
file = "home/pi/Desktop/image.jpg"

cv2.imwrite(file, camera_capture)

del(camera)

任何人都知道如何修复它,并且阈值窗口不会出现

qkf9rpyu

qkf9rpyu1#

documentation表示VideoCapture.read()
在一个调用中合并VideoCapture::grab()和VideoCapture::retrieve()
和VideoCapture::retrieve()
解码并返回刚抓取的帧。如果没有抓取帧(摄像机已断开连接,或者视频文件中没有更多帧),则方法返回false,函数返回NULL指针。
在python中,您必须预期retvarframe,其中frame不是None,只有当retvalTrue时。
在你的代码中,这一行:

# read image
ret, img = cap.read()

可能会给予你img为None,所以当你尝试在这里裁剪它时:

crop_img = img[100:300, 100:300]

你得到你的错误:
“TypeError:'NoneType'对象不是可订阅的
你需要先测试retval:

retval, img = cap.read()
if retval:
    # get hand data from the rectangle sub window on the screen
    cv2.rectangle(img, (300, 300), (100, 100), (0, 255, 0), 0)
    crop_img = img[100:300, 100:300]
    ...

或者首先测试img是否不为None:

# Since we don't use the return value let's just forget it
_, img = cap.read()
if img is not None:
    # get hand data from the rectangle sub window on the screen
    cv2.rectangle(img, (300, 300), (100, 100), (0, 255, 0), 0)
    crop_img = img[100:300, 100:300]
    ...

然后你必须处理get_image函数没有得到图像的事实(要么返回None,要么引发Exception)。

  • 旁注:你的代码仍然有两个问题,你在函数的末尾有一行all_img = np.hstack((drawing, crop_img)),但你从来没有使用all_img。在模块的最后,你做了一个del(camera),但相机从来没有定义。最后,如果你必须公开分享你的代码,请遵循PEP8(在你的编辑器或选择中安装pylint或只是flake8)*。
ddarikpa

ddarikpa2#

试着像这样修改“while”:这样它将读取所有的帧并剪切它们

import cv2  
cap = cv2.VideoCapture('t8.mp4')

# x,y,h,w are the sizes you want to cut:
x=0 
y=0 
w=650 
h=750

success, frame = Image.read()

while success :
    success, frame = Image.read()
        
    if success: 
        cropeedIMAGE = frame[y:y+h, x:x+w]
        cv2.imshow('finger', cropeedIMAGE)
        
    if cv2.waitKey(10) & 0xFF == ord('q'):
            break

cv2.destroyAllWindows()
o2g1uqev

o2g1uqev3#

尝试将cap = cv2.VideoCapture(0)更改为cap = cv2.VideoCapture(1)cap = cv2.VideoCapture(2)cap = cv2.VideoCapture(3) ...

相关问题