[用cv2.imwrite()编写pgm图像

问题描述 投票:0回答:1

我想在openCV中使用经过caffe预训练的模型来编写检测到的图像,并且它可以与jpg或其他类似格式一起使用,但是显示错误

SystemError: <built-in function imwrite> returned NULL without setting an error

这是我的代码

import os
import cv2
import numpy
from imutils import paths

# DIR_PATH = os.path.dirname(os.path.realpath('dataset/'))



DIR_PATH = (list(paths.list_images('dataset')))

print(DIR_PATH)

if not os.path.exists('Output'):
    os.makedirs('Output')

MODEL = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')


# print(DIR_PATH)
for file in DIR_PATH:
    filename, file_extension = os.path.splitext(file)

    if (file_extension in ['.png', '.jpg', '.pgm', '.jpeg']):
        image = cv2.imread(file)
        (h, w) = image.shape[:2]

        print("Proccess one started ")
        blob = cv2.dnn.blobFromImage(cv2.resize(
            image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123, 0))

        MODEL.setInput(blob)
        detections = MODEL.forward()  
        print("Proccess Two started ")
        COUNT = 0
        for i in range(0, detections.shape[2]):
            box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            confidence = detections[0, 0, i, 2]

            if confidence > 0.165:
                cv2.rectangle(image, (startX, startY), 
                            (endX, endY), (0, 255, 0), 2)
                COUNT = COUNT + 1

        export_name = filename.split("\\")
        print(export_name)

        if file_extension == '.pgm' :
            cv2.imwrite('Output/'+export_name[1]+export_name[2], image, 0)
        else:
            cv2.imwrite('Output/'+export_name[1]+file_extension, image)




        print("Face detection complete for image " +
              file + " (" + str(COUNT) + ") faces found!")

而且我也检查了我的价值观。具有PGM格式的图像已加载,但是正在检测人脸,但是人脸数量过多,并且无法使用cv2.imwrite进行写入]

这里是确切的问题

  if file_extension == '.pgm' :
            cv2.imwrite('Output/'+export_name[1]+export_name[2], image, 0)
        else:
            cv2.imwrite('Output/'+export_name[1]+file_extension, image)
python opencv conv-neural-network caffe pgm
1个回答
0
投票

OpenCV不读取OS路径或PathLib格式的路径,它读取字符串,因此将代码更改为:

if file_extension == '.pgm':
            fname = 'Output/{}{}'.format(export_name[1],export_name[2])
            cv2.imwrite(fname, image, 0)
        else:
            fname = 'Output/{}{}'.format(export_name[1],file_extension)
            cv2.imwrite(fname, image)
© www.soinside.com 2019 - 2024. All rights reserved.