Python:保存图片到指定目录下的文件中(若不存在则创建)

关键部分代码:

            self.numbers=6
            path = "./picture/" + str(self.numbers)
            if not os.path.exists(path):
                os.makedirs(path)
            path = "./picture/" + str(self.numbers)+"/"
            if self.count_picture<101:
                self.display_text()
                cv2.imwrite(path + str(self.numbers) + '.' + str(self.count_picture) + '.jpg', gray1[y:y+h, x:x+w])
                self.count_picture += 1

整个函数的代码

    def save_picture(self):
        face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")  # opencv的人脸识别库
        ret, self.image = self.cap.read()  # 从视频流中读取
        gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
        gray1 = gray.copy()
        self.faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        # 画矩形框
        for (x, y, w, h) in self.faces:
            cv2.rectangle(self.image, (x, y), (x + w, y + h), (255, 0, 0), 2)  # 框的颜色\
            self.numbers=6
            path = "./picture/" + str(self.numbers)
            if not os.path.exists(path):
                os.makedirs(path)
            path = "./picture/" + str(self.numbers)+"/"
            if self.count_picture<101:
                self.display_text()
                cv2.imwrite(path + str(self.numbers) + '.' + str(self.count_picture) + '.jpg', gray1[y:y+h, x:x+w])
                self.count_picture += 1
                if self.count_picture == 100:
                    QMessageBox.information(self, '提示', '人脸检测已经完成')
                    self.timer_camera_save_picture.stop()
                    self.show_camera()
                    self.timer_camera.start(30)  # 定时器开始计时30ms,结果是每过30ms从摄像头中取一帧显示
        # 显示
        show = cv2.resize(self.image, (640, 480))  # 把读到的帧的大小重新设置为 640x480
        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)  # 视频色彩转换回RGB,这样才是现实的颜色
        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0],QtGui.QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式
        self.label_show_camera.setPixmap(QtGui.QPixmap.fromImage(showImage))  # 往显示视频的Label里 显示QImage

你可能感兴趣的:(python,opencv,计算机视觉)