pythonopencvconv-neural-networkcaffepgm

writing pgm images with cv2.imwrite()


I want to write my detected images with caffe pre-trained model in openCV and it works with jpg or other similar formats but it's showing an error

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

and here is my code

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!")

and also I've checked my values. images with PGM format has been loading but and detecting faces but the number of faces is too much and it's not writing at all with cv2.imwrite

here is the exact problem

  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)

Solution

  • OpenCV does not read paths in OS paths or PathLib formats, it reads a string so change your code to:

    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)