Segmentation fault in recognize_ndarray OpenALPR - python

I’m trying to detect plates using openalpr + python with an IP cam, but I’m getting the following error:
The openalpr version is the Open Source.
I've alrealdy tryied before recognize_file function, unscessufully
Fatal Python error: Segmentation fault
Current thread 0x00007fa8c2fee740 <python> (most recent call first):
File "/usr/lib/python2.7/dist-packages/openalpr/openalpr.py", line 184 in recognize_ndarray
File "main9.py", line 45 in main
File "main9.py", line 59 in <module>
Bellow the code:
import numpy as np
import cv2
from openalpr import Alpr
import sys
import faulthandler; faulthandler.enable()
RTSP_SOURCE = 'rtsp://user:pass#ip:port/cam/realmonitor?channel=1&subtype=0'
WINDOW_NAME = 'openalpr'
FRAME_SKIP = 15
def main():
alpr= Alpr("us", "/etc/openalpr/openalpr.conf", "/home/alan/openalpr/runtime_data")
if not alpr.is_loaded():
print('Error loading OpenALPR')
sys.exit(1)
alpr.set_top_n(3)
alpr.set_default_region('pa')
cap = cv2.VideoCapture(RTSP_SOURCE)
cv2.namedWindow('op', cv2.WINDOW_NORMAL)
if not cap.isOpened():
alpr.unload()
sys.exit('Failed to open video file!')
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE)
cv2.setWindowTitle(WINDOW_NAME, 'OpenALPR video test')
_frame_number = 0
while True:
ret_val, frame = cap.read()
if not ret_val:
print('VidepCapture.read() failed. Exiting...')
break
_frame_number += 1
if _frame_number % FRAME_SKIP != 0:
continue
cv2.imshow(WINDOW_NAME, frame)
results = alpr.recognize_ndarray(frame)
for i, plate in enumerate(results['results']):
best_candidate = plate['candidates'][0]
print('Plate #{}: {:7s} ({:.2f}%)'.format(i, best_candidate['plate'].upper(), best_candidate['confidence']))
if cv2.waitKey(1) == 27:
break
cv2.destroyAllWindows()
cap.release()
alpr.unload()
if __name__ == "__main__":
main()
Does anybody faced this error before?

I know this is a very old post but I've currently been working on a very similar project and came across this very same issue. experimenting around with the code led me to discover that if you include the following lines of code in a function python will throw a segmentation error:
alpr =Alpr("eu","/etc/openalpr/openalpr.conf","/usr/share/openalpr/runtime_data")
alpr.unload()
Luckily however you only need to run these lines once in a python script to be able to use openalpr so run the first line just at the start of your code before the function is called and run the second line only after you've finished using the function.

Related

OpenCV; Read Camera on macOS; TypeError

I try to run a camera reading code in macOS. Here is my code:
import cv2
from pyzbar.pyzbar import decode
import os
os.system("clear")
cap = cv2.VideoCapture(0)
cap.set(3 , 640)
cap.set(4 , 480)
while True:
success, img = cap.read()
for barcode in decode(img):
print(barcode.data)
print(barcode.rect)
x = barcode.data.decode('utf-8')
print(x)
cv2.imshow('Result', img)
cv2.waitKey(1)
This is current error:
Traceback (most recent call last):
File "/Users/username/Documents/Pyzbar Lesson 2.py", line 21, in <module>
for barcode in decode(img):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 207, in decode
pixels, width, height = _pixel_data(image)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 173, in _pixel_data
pixels, width, height = image
TypeError: cannot unpack non-iterable NoneType object
Please, share if I miss anything or other error in the code.
Thanks.
This code works fine on my Windows machine (after changing 'clear' to 'cls' of course).
You're getting a Type Error because decode is trying to operate on a None type. In line 21 you call for barcode in decode(img). Here it is img that is 'None` and since decode cannot handle 'None' you get the error.
I suspect that your hardware is not cooperating properly. This could be due to your camera access preferences. You can use the cap.isOpen() and cap.isValid() checks to add an additional layer of trouble shooting.
I FINALLY FOUND THE ANSWER
Apparently, for some macOS users, having 'cap.set()' in your code would give you errors. But after removing it, it works perfectly
'''
import cv2
from pyzbar.pyzbar import decode
import os
os.system("clear")
cap = cv2.VideoCapture(0)
while True:
success, img = cap.read()
if not success:
break
for barcode in decode(img):
print(barcode.data)
print(barcode.rect)
x = barcode.data.decode('utf-8')
print(x)
cv2.imshow('Result', img)
cv2.waitKey(1)
'''

Why am I getting "cv2.error: Unknown C++ exception from OpenCV code" when I'm using cv2.BackgroundSubtractorKNN() in Python?

A simple program to show the feed from my webcam is running fine. I'm getting the error only when I try to run cv2.BackgroundSubtractorKNN() within the loop.
I have applied the following fix:
Uninstalled the latest version of OpenCV (which I was using) and installed an older version 4.5.4. But the error still persists.
Here's my code and the corresponding messages in the terminal.
import cv2
cap = cv2.VideoCapture(0)
mog = cv2.BackgroundSubtractorKNN()
while(True):
ret, frame = cap.read()
fgmask = mog.apply(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Message in terminal
PS D:\Python ground up\Open_CV> python -u "d:\Python ground up\Open_CV\backgroundsub.py"
Traceback (most recent call last):
File "d:\Python ground up\Open_CV\backgroundsub.py", line 7, in <module>
fgmask = mog.apply(frame)
cv2.error: Unknown C++ exception from OpenCV code
I think it's createBackgroundSubtractorKNN not BackgroundSubtractorKNN

Python OpenCV Camera Error

For some reason, I cannot read camera video data using OpenCV and Python 3.
Here is the code I am using:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
_, frame = cap.read()
cv2.imshow('frame',frame)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
This code returns the following error:
Traceback (most recent call last):
File "C:\Path\To\File\VideoTest.py", line 10, in <module>
cv2.imshow('frame',frame)
cv2.error: D:\Build\OpenCV\opencv-3.3.1\modules\highgui\src\window.cpp:339: error: (-215) size.width>0 && size.height>0 in function cv::imshow
The computer is running Windows Server 2012 R2 and has one USB webcam permanently in use in addition to the new one I am trying to read data from. I have tried changing the line cap = cv2.VideoCapture(0) to cap = cv2.VideoCapture(1) and had an identical error.
I tried replicating the error on my laptop using the same code and USB webcam, but it worked perfectly and I was able to stream the video.
**EDIT**
To debug, I ran the following program line-by-line in the Python shell.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
print(cap.read())
cap = cv2.VideoCapture(1)
print(cap.read())
The code outputted (False, None) twice.

how to run webcam through python on rpi3

I am trying to use a MS lifecam with my raspberry-pi-3. It works on the command line, when I type the following command:
$ fswebcam img.jpg
Trying source module v4l2...
/dev/video0 opened.
...
Writing JPEG image to 'img.jpg' # this works fine
Now I want to run the camera through a python code:
import pygame
import pygame.camera
from pygame.locals import *
DEVICE = '/dev/video0'
SIZE = (640, 480) # I also tried with img size (384,288), same error
FILENAME = 'capture.jpg'
pygame.init()
pygame.camera.init()
camera = pygame.camera.Camera(DEVICE, SIZE)
camera.start() # error on executing this line
pygame.image.save(screen, FILENAME)
camera.stop()
The reported error is:
SystemError: ioctl(VIDIOC_S_FMT) failure: no supported formats
I am puzzled here. The camera is supported by rasp-pi, so it looks like my python code has to be updated somewhere. Can you help?
Try use this:
camera = pygame.camera.Camera(pygame.camera.list_cameras()[0])
camera.start()
img = camera.get_image()
pygame.image.save(img, FILENAME)
Had problem and once I stopped a process using the video stream the error was resolved.
details
I had the same problem. And while
/dev/video0
was listed, camera.start() resulted in the same error.
I had ran
sudo motion
earlier. so I verified the service was running, stopped it, then tried pygame. and it worked.
sudo service --status-all
sudo service motion stop
you can also use this :
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
cv2.destroyWindow("preview")

2 webcam feed doesn't work opencv

I'm using ubuntu 13.10 along with opencv 2.4.9 with python 2.7.
I have written the following code but it seems to fails on runtime.
import cv2
c1=cv2.VideoCapture(2) #camera id
c2=cv2.VideoCapture(1) #camera id
while(True):
ret,frame = c1.read()
ret,frame2 = c2.read()
frame = cv2.cvtColor(frame,0)
frame2 = cv2.cvtColor(frame2,0)
cv2.imshow('frame',frame)
cv2.imshow('frame2',frame2)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
c1.release()
c2.release()
cv2.destroyAllWindows()
But on running this in Ubuntu i get the following error :
VIDIOC_QUERYMENU: Invalid argument
libv4l2: error turning on stream: Invalid argument
VIDIOC_STREAMON: Invalid argument
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file
/build/buildd/opencv-2.4.5+dfsg/modules/imgproc/src/color.cpp, line 3358
Traceback (most recent call last):
File "/home/bini/KV/IP_Proj/webcam basics opencv.py", line 8, in <module>
frame2 = cv2.cvtColor(frame2,0)
cv2.error: /build/buildd/opencv-2.4.5+dfsg/modules/imgproc/src/color.cpp:3358: error:
(-215) scn == 3 || scn == 4 in function cvtColor
The same code used to work fine on windows.
Can someone help me please as to why is this occuring..??? i have on idea.
Thanks in advance
For linux,if you're using 1 camera , at first you must change your camera id to 0 , but it seems that you want use 2 camera , this is because the resolution, framerate and protocol used by your cameras overloads the USB connection so read this link! also this is a base code for connect and use linux webcam:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
#set the width and height, and UNSUCCESSFULLY set the exposure time
cap.set(3,1080)
cap.set(4,1024)
cap.set(15, 0.1)
while True:
ret, img = cap.read()
cv2.imshow("input",img)
key = cv2.waitKey(10)
if key == 27:
break
cv2.destroyAllWindows()
cv2.VideoCapture(0).release()
One (or both) of your cameras isn't initializing correctly. I just ran your code on my machine (Ubuntu 14.04) and both frames come up showing live views from my two connected cameras. Can you view both cameras in cheese or guvcview?
I do get a bunch of these messages:
VIDIOC_QUERYMENU: Invalid argument
errors but neither of these:
libv4l2: error turning on stream: Invalid argument
VIDIOC_STREAMON: Invalid argument

Categories

Resources