Python:类型错误:元组索引必须是整数,而不是元组

时间:2017-04-18 18:32:11

标签: python-2.7 opencv numpy motion-detection

我正在计算黑色像素的数量,以检测运动并得到此错误tuple indices must be integers, not tuple如果有人能告诉我我搞砸了哪里,我将不胜感激。下面是我的代码。

class MotionDetectorInstantaneous():

    def onChange(self, val): #callback when the user change the detection threshold
        self.threshold = val

    def __init__(self,threshold=15, doRecord=True, showWindows=True):
        self.writer = None
        self.font = None
        self.doRecord=doRecord #Either or not record the moving object
        self.show = showWindows #Either or not show the 2 windows
        self.frame = None

        self.capture = cv2.VideoCapture(0)

        self.capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1280)
        self.capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 720)

        self.width = int(self.capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
        self.height = int(self.capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))

        self.capture.grab()
        rval, self.frame = self.capture.retrieve()


        if doRecord:
            self.initRecorder()

        self.frame1gray = np.zeros((self.height,self.width,3), np.uint8)
        print "2: frame1gray type: ",type(self.frame1gray) , np.size(self.frame1gray)
        self.frame1gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)

        self.res = np.zeros((self.height,self.width,3), np.uint8)
        print "3: res type: ",type(self.res) , np.size(self.res)


        self.frame2gray = np.zeros((self.height,self.width,3), np.uint8)
        print "4: frame2gray type: ",type(self.frame2gray) , np.size(self.frame2gray)


        self.width = self.width
        print "width",self.width
        self.height = self.height
        print "height", self.height
        self.nb_pixels = self.width * self.height
        self.threshold = threshold
        self.isRecording = False
        self.trigger_time = 0 #Hold timestamp of the last detection

        if showWindows:
            cv.NamedWindow("Image")
            cv.CreateTrackbar("Detection treshold: ", "Image", self.threshold, 100, self.onChange)

    def initRecorder(self): #Create the recorder

        codec = cv2.cv.FOURCC('M', 'J', 'P', 'G')
        self.writer=cv2.VideoWriter(datetime.now().strftime("%b-%d_%H_%M_%S")+".wmv", codec, 5, (self.width, self.height), 1)

    def run(self):
        started = time.time()
        while True:

            self.capture.grab()
            rval, curframe = self.capture.retrieve()

            print "6: curframe type: ",type(curframe) , np.size(curframe)
            instant = time.time() #Get timestamp o the frame

            self.processImage(curframe) #Process the image

            if not self.isRecording:
                if self.somethingHasMoved():
                    self.trigger_time = instant #Update the trigger_time
                    if instant > started +5:#Wait 5 second after the webcam start for luminosity adjusting etc..
                        print datetime.now().strftime("%b %d, %H:%M:%S"), "Something is moving !"
                        if self.doRecord: #set isRecording=True only if we record a video
                            self.isRecording = True
            else:
                if instant >= self.trigger_time +10: #Record during 10 seconds
                    print datetime.now().strftime("%b %d, %H:%M:%S"), "Stop recording"
                    self.isRecording = False
                else:
                    #cv.PutText(curframe,datetime.now().strftime("%b %d, %H:%M:%S"), (25,30),self.font, 0) #Put date on the frame
                    cv.WriteFrame(self.writer, curframe) #Write the frame


            if self.show:
                cv.ShowImage("Image", curframe)
                cv.ShowImage("Res", self.res)

            cv.Copy(self.frame2gray, self.frame1gray)
            c=cv.WaitKey(1) % 0x100
            if c==27 or c == 10: #Break if user enters 'Esc'.
                break            

    def processImage(self, frame):
        self.frame2gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        self.res = cv2.absdiff(self.frame1gray, self.frame2gray)


        self.res = cv2.GaussianBlur(self.res, (15, 15), 0)

        kernel = np.ones((3, 3), np.uint8)
        self.res = cv2.morphologyEx(self.res, cv2.MORPH_OPEN, kernel)
        self.res = cv2.morphologyEx(self.res, cv2.MORPH_GRADIENT, kernel)

        self.res = cv2.threshold(self.res, 10, 255, cv2.THRESH_BINARY_INV)

    def somethingHasMoved(self):
        nb=0 #Will hold the number of black pixels

        for x in range(self.height): #Iterate the hole image
            print "row", x
            for y in range(self.width):
                print "col", y
                if self.res[x,y] == 0.0: #If the pixel is black keep it
                    nb += 1
    print "black pixels: ", nb
    print "total pixels: ", self.nb_pixels
        avg = (nb*100.0)/self.nb_pixels #Calculate the average of black pixel in the image
    print"average movement : ",avg
        if avg > self.threshold:#If over the ceiling trigger the alarm
            return True
        else:
            return False
if __name__=="__main__":
    detect = MotionDetectorInstantaneous(doRecord=True)
    detect.run()

在此功能的上方代码def somethingHasMoved(self):我到了if self.res[x,y] == 0.0:

0 个答案:

没有答案