First time asking, I havent found any answers to this after some days of looking. Also im absolutely not a programming pro so I might have missed something obvious.
I am running a code that goes through a large library of images (some 2M) and extracts information from them. The code runs fine for several iterations (20-10000ish) but then the program just stops without any errors reported.
The main code exits (terminates?) most of the time at an OpenCV edge detection or houghlines, but not all the time. about 10% of the time it is at some other point in the code.
Using:
OpenCV 4.1.1
Python 3.7.1
Windows 10
Image at: https://www.dropbox.com/s/5lfzkw6sqmu73eb/Image_00_00_00_00.bmp?dl=0
I have tried to get an exception from the Opencv code in some ways, but nothing pops up. The latest attempt is in the code below.
I have tried to use the trace and log modules but I cant really get them to do anything useful.
import numpy as np
import cv2
import traceback
import sys
def cropping_points2(img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Gray image needed for edge detection
try:
edges = cv2.Canny(gray,20,70,apertureSize = 3)
except Exception as e:
print(traceback.format_exc())
print(sys.exc_info())
print(e, 'there was actually an exception!')
exit()
lines = []
try:
lines = cv2.HoughLines(edges,3,np.pi/180,65, 50, 10, min_theta = 1.4, max_theta = 1.75) # analyse image to find lines - thetha setting looks for horizontal
except Exception as e:
print(traceback.format_exc())
print(sys.exc_info())
print(e, 'there was actually an exception!')
exit()
if lines is None: # All black images return a NoneType image
print('no lines!') # Capture NoneType without crashiing
rect = []
has_lines = False
return rect , has_lines
has_lines = True
return lines[0][0], has_lines
if __name__ == "__main__":
img= cv2.imread('Image_00_00_00_00.bmp')
for index in range(10000):
rect, has_lines = cropping_points2(img)
print(rect)
print(index)
I expect the program to give me a hint of why it stops running =|
Related
import time
import pyautogui
location = pyautogui.locateOnScreen('ok.png')
pyautogui.click(location)
HOW DO I WRITE THE FOLLOWING STATEMENT AS CODE?
If image is no found on screen, keep running location until the image is found.
otherwise the code is terminating immediately.
I tried :
While location == None : #Or location == False
pyautogui.click(location)
Try using while like this:
while location is not None:
pyautogui.click(location)
According to the Pyautogui documentation:
If the image can’t be found on the screen, locateOnScreen() raises ImageNotFoundException
This means that you have to handle the error message in order to keep the program running in case the image is not there.
Try using exception handling:
import pyautogui
while True:
# Try to do this
try:
location = pyautogui.locateOnScreen('ok.png')
# Location found with no errors: break the while loop and proceed
break
# If an error has occurred (image not found), keep waiting
except:
pass
pyautogui.click(location)
NOTE: This generates an infinite loop until the image is found on screen. To break this loop and stop the script execution use CTRL+C on the Shell.
In alternative you may set a maximum time waiting for the image:
import time
import pyautogui
max_wait = 30 # Seconds
end = time.time() + max_wait
while time.time() <= end:
# Try to do this
try:
location = pyautogui.locateOnScreen('ok.png')
# Location found with no errors: break the while loop and proceed
break
# If an error has occurred (image not found), keep waiting
except:
pass
pyautogui.click(location)
I have an app in which I read two RTSP streams from a hikvision camera and I do things with. There are two streams because it is a thermal camera and it has two streams, a normal stream and a thermal stream.
This is how I read the streams:
import cv2
normal_path = "rtsp://adress#192.168.1.120/Streaming/channels/102"
thermal_path = "rtsp://adress#192.168.1.120/Streaming/channels/201"
normal_capture = cv2.VideoCapture(normal_path)
thermal_capture = cv2.VideoCapture(thermal_path)
while True:
try:
ret,thermal_frame = thermal_capture.read(0)
ret1,normal_frame = normal_capture.read(0)
#do a lot of things
except:
continue
normal_capture.release()
thermal_capture.release()
cv2.destroyAllWindows()
The problem is that, after a while, for example, after 5 hours in which the app worked fine, it recives an error like this:
[h264 # 0x2ac51c0] error while decoding MB 17 1, bytestream -27
Any idea why is this happening? Do you know why this error goes over the try and except ?
I ran into the same problem with a single stream, although I was encountering it much sooner (a small number of minutes into the stream). I handle it by checking if ret is not True
and if so, rebuilding the stream.
import cv2
thermal_path = "rtsp://adress#192.168.1.120/Streaming/channels/201"
thermal_capture = cv2.VideoCapture(thermal_path)
while True:
ret, thermal_frame = thermal_capture.read(0)
if not ret:
thermal_capture.release()
thermal_capture = cv2.VideoCapture(thermal_path)
print('Found error; rebuilding stream')
#do a lot of things
thermal_capture.release()
cv2.destroyAllWindows()
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.
I can't see any difference between
import pyautogui
pyautogui.locateOnScreen("anImage")
and
import pyautogui
pyautogui.locateOnScreen("anImage", minSearchTime=10)
And there is no explanation nor reference in documentation about minSearchTime.
It's useful when you want to wait some time for an image to appear. PyAutoGUI will keep making screenshots and searching for the image until the minSearchTime has passed.
I got this from the source code:
def locateOnScreen(image, minSearchTime=0, **kwargs):
"""minSearchTime - amount of time in seconds to repeat taking
screenshots and trying to locate a match. The default of 0 performs
a single search.
"""
start = time.time()
while True:
try:
screenshotIm = screenshot(region=None) # the locateAll() function must handle cropping to return accurate coordinates, so don't pass a region here.
retVal = locate(image, screenshotIm, **kwargs)
try:
screenshotIm.fp.close()
except AttributeError:
# Screenshots on Windows won't have an fp since they came from
# ImageGrab, not a file. Screenshots on Linux will have fp set
# to None since the file has been unlinked
pass
if retVal or time.time() - start > minSearchTime:
return retVal
except ImageNotFoundException:
if time.time() - start > minSearchTime:
raise
When I am calling the .read() method then my program crashes (with .avi format). My program runs with other formats (.ogv, .mkv) but in that case type(last_frame) == None. Is there any solution to fix these errors?
import cv2
import numpy as np
in_file = r'C:\Users\Johnny\Desktop\zola\animation.avi'
print(in_file)
cap = cv2.VideoCapture(in_file)
print(cap)
ret, last_frame = cap.read() # the program works without this line
try:
if not cap.isOpened() : raise("damn!")
except TypeError as err:
print(err)
Output:
C:\Users\Johnny\Desktop\zola\animation.ogv
<VideoCapture 02843110>
exceptions must be old-style classes or derived from BaseException, not str