TypeError: crop() takes from one to two positional arguments but three were given

TypeError: crop() takes from one to two positional arguments but three were given

我一直在使用 numpy、PIL 和 OpenCV 来创建人脸检测和处理系统。我想做的是在边界框周围裁剪(用于我尚未编写的进一步处理),所以我写了以下内容:

import cv2
import numpy as np
from PIL import Image 
def main():
    #Creates a camera object
    vidCapture = cv2.VideoCapture(0)
    while 1:
        faceDetector = FaceDetector()
        #stores the current frame into the frame variable
        ret, frame = vidCapture.read()
        #detects any faces and draws bounding boxes around them
        img = faceDetector.find_any_faces(frame)
        processing = Processing()
        #crops everything around the bounding boxes for the faces
        processing.mask(frame, faceDetector.getPoint1(), faceDetector.getPoint2())

class Processing():

    #masks around the bounding boxes for the face
    def mask(self, image, p1, p2):
        #creates a numpy array from the image
        arrimg = np.array(image)
        #creates a PIL Image from the np array
        img = Image.fromarray(arrimg)

        #crops around each bounding box
        cropped_image = img.crop(p1, p2)
        return cropped_image

这会引发 TypeError 消息:"crop() takes from 1 to 2 positional arguments but 3 were given"。据我所知,那些通常来自不包括 self 作为方法的参数,但我在代码中包括了我的。如果有人能提供帮助,那就太好了!

img.crop() 将单个元组作为参数(第二个是已经添加的 self )。当你传递 2 时,它以三个参数结束,这会给你一个错误:

Image.crop(box=None)

Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.

Parameters: box – The crop rectangle, as a (left, upper, right, lower)-tuple.

您可以将您的元组加在一起形成一个 4 元素元组:

img.crop(p1 + p2)

或传播它们:

img.crop((*p1, *p2))