[ОШИБКА] предупреждение libpng: ширина изображения равна нулю в ihdr с использованием OpenCV и Python - PullRequest
0 голосов
/ 08 февраля 2019

Я работаю над небольшим кодом, где GPIO-триггер будет делать снимки с 3 веб-камер на RPi3 с opencv.

Вот мой код:

import numpy as np
import cv2
import datetime
import RPi.GPIO as GPIO
import os
import os.path
from time import gmtime, strftime
import time

#ini GPIO to get the trigger for cooling pause
GPIO_trigger=21
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_trigger, GPIO.IN, pull_up_down=GPIO.PUD_UP)


#Create a list with all pluged-in Cameras
usblist=[0,1,2]
PATH="/home/pi/opencv-3.4.3/python_project/"

def csnip(channel):

    #Number of frames to throw away while the camera adjusts to light levels
    ramp_frames = 30
    for Kn in usblist:
        #set name for Video with camera name and Timestamp
        Kn=str(Kn)
        time_stamp = strftime("%Y-%m-%d_%H:%M:%S", gmtime())
        Kameran="KRASP"
        name=str(time_stamp) + "KRASP" + Kn

        directory = str(PATH + "KRASP" +Kn)
        if not os.path.exists(directory):
            os.makedirs(directory)



        camera_port = Kn

        #Number of discarded frames
        ramp_frames = 30

        camera = cv2.VideoCapture(camera_port)

        def make_1080p():
            camera.set(3, 1920)
            camera.set(4, 1080)

        def make_720p():
            camera.set(3, 1280)
            camera.set(4, 720)

        def make_480p():
            camera.set(3, 640)
            camera.set(4, 480)

        def change_res(width, height):
            camera.set(3, width)
            camera.set(4, height)

        make_720p()
        #change_res(1280, 720)


        # Captures a single image from the camera
        def get_image():
            retval, im = camera.read()
            return im

        for i in range(ramp_frames):
         temp = get_image()
        # Take the actual image we want to keep
        camera_capture = get_image()
        file = PATH+"KRASP"+Kn+"/"+name+".png"
        print("Saving pic...")
        cv2.imwrite(file, camera_capture)
        del(camera)
        time.sleep(2)

#When a falling trigger in detected on the GPIO, uses callback function and sleeps for 2s        
GPIO.add_event_detect(GPIO_trigger, GPIO.FALLING, callback=csnip, bouncetime=2000)

try:
    while True: 
        time.sleep(0.01)

except KeyboardInterrupt:  
    GPIO.cleanup()       # clean up GPIO on CTRL+C exit

GPIO.cleanup()            # clean up GPIO on normal exit  

код работает нормально, но я не могу открыть картинку.я получаю следующий вывод консоли:

Saving pic...
libpng warning: Image width is zero in IHDR
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data

Что действительно странно, так это то, что у меня есть похожий код, который работает отлично, с теми же функциями и т. д.

import numpy as np
import cv2
import datetime
#import RPi.GPIO as GPIO
import os
import os.path
from time import gmtime, strftime

#ini GPIO to get the trigger for cooling pause
#GPIO_trigger=7
#GPIO.setmode(GPIO.BOARD)
#GPIO.setup(GPIO_trigger, GPIO.IN)

#
Camera=int(input("How many Cameras are plugged in RPi?"))
i=0
#Create a list with all pluged-in Cameras
usblist=[]

PATH="/home/pi/opencv/KameraPi/"

def set_name(Kn):
    #set name for Video with camera name and Timestamp
    Kn=str(Kn)
    time_stamp = strftime("%Y-%m-%d_%H:%M:%S", gmtime())
    Kameran="KRASP"
    name=time_stamp + Kameran + Kn
    return name

def img_save(set_name):
    # Camera number Kn 
    camera_port = Kn

    #Number of discarded frames
    ramp_frames = 30

    camera = cv2.VideoCapture(camera_port)

    def make_1080p():
        camera.set(3, 1920)
        camera.set(4, 1080)

    def make_720p():
        camera.set(3, 1280)
        camera.set(4, 720)

    def make_480p():
        camera.set(3, 640)
        camera.set(4, 480)

    def change_res(width, height):
        camera.set(3, width)
        camera.set(4, height)

    make_720p()
    #change_res(1280, 720)


    # Captures a single image from the camera
    def get_image():
        retval, im = camera.read()
        return im

    for i in range(ramp_frames):
     temp = get_image()
    # Take the actual image we want to keep
    camera_capture = get_image()
    file = str(PATH+usblist[Kn]+"/"+set_name+".png")
    print("Saving pic...")
    cv2.imwrite(file, camera_capture)
    del(camera)


#Add Cameras to the list
while i < Camera:
    usbname="KRASP"+str(i)
    usblist.append(usbname)
    i=i+1

listlength=len(usblist)

#Creat a folder for each Camera in the list if it doesn't exist already
for usb in usblist:
    directory = str(PATH + usb)
    if not os.path.exists(directory):
        os.makedirs(directory)


#Temporary solution: Film and save video for given Camera (max 4 Camera)   
while True:
    print(usblist)
    mchoice = int(input ("Take a picture with what Camera? "))
    if mchoice == '':
        break
    else:
        mchoice = int(float(mchoice))
        if mchoice==0:
            Kn=mchoice
            img_save(set_name(Kn))

        elif mchoice==1:
            Kn=mchoice
            img_save(set_name(Kn))

        elif mchoice==2:
            Kn=mchoice
            img_save(set_name(Kn))

        elif mchoice==3:
            Kn=mchoice
            img_save(set_name(Kn))

Последнийкод запускается на пользовательском вводе, но он должен делать то же самое ... и без ошибок на этом.У кого-то есть подсказка, что не так с запущенным?Спасибо

...