Gym wrapper videorecorder is not working properly on Hopper-v2 environment. Gives segmentation fault - python-3.x

I am trying to save a video of the render of my Hopper-v2 environment, however it gives a segmentation fault error. I have made a short code example to reproduce the issue.
import os
from gym.wrappers.monitoring.video_recorder import VideoRecorder
path_project = os.path.abspath(os.path.join(__file__, ".."))
path_of_video_with_name = os.path.join(path_project, "videotest.mp4")
env = gym.make('Hopper-v2') # for making environment
state = env.reset()
video_recorder = None
video_recorder = VideoRecorder(env, path_of_video_with_name, enabled=True)
for _ in range(1000):
env.render()
video_recorder.capture_frame()
env.step(env.action_space.sample()) # take a random action
print("Saved video.")
video_recorder.close()
video_recorder.enabled = False
env.close()
This gives the error:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
It does create a video though, which is only 14 frames long, then it gets interrupted. By commenting out the 'video_recorder.capture_frame()' line, it will render the complete episode. Using the cartpole environment instead of the hopper, does work and saves the complete episode.
I am using Linux 20.0.4 (Ubuntu), Gym version 0.21.0 using pip install gym, python version 3.7.6.
If anyone has any idea, please let me know

Install the following dependencies;
pip install ffmpeg
pip install imageio-ffmpeg
Resolved my issue.

Related

PyMC3 fails to execute on MacOS Big Sur/ PyCharm

I am attempting to run some simple PyMC3 code in PyCharm on MacOS Big Sur but the execution fails and throws the following error:
Exception: ('Compilation failed (return status=1): ld: library not found for -lSystem. clang-10: error: linker command failed with exit code 1 (use -v to see invocation). ', '[Elemwise{add,no_inplace}(TensorConstant{1.0}, TensorConstant{1.0})]')
I am using PyCharm 2020.3.2. I am able to install pymc3 (version 3.8) and theano (1.0.4) into the environment. Code I am attempting to run follows:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import pymc3 as pm
np.random.seed(123)
n_experiments = 4
theta_real = 0.35
data = stats.bernoulli.rvs(p=theta_real, size=n_experiments)
with pm.Model() as our_first_model:
theta = pm.Beta('theta', alpha=1, beta=1)
y = pm.Bernoulli('y', p=theta, observed=data)
start = pm.find_MAP()
step = pm.Metropolis()
trace = pm.sample(1000, step=step, start=start)
burnin = 100
chain = trace[burnin:]
pm.traceplot(chain, lines={'theta':theta_real});
I disabled Apple System Integrity Protection on some speculation that maybe Apple hiding /usr/include might be the source of the problem; it made no difference. No clue how else to fix this.
From the information in comments it seems like your anaconda is broken.
Update anaconda and try again.
If that doesn't work, try to install PyMC3 in the system Python not the Anaconda one.
This will use the system clang and not the Anaconda clang.

OpenCV- Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) on MAC

Getting Error Like
Process finished with exit code 139 (interrupted by signal 11:
SIGSEGV)
when i run below code in pycharm.
import cv2
img = cv2.imread("MyFriends.jpg")
cv2.imshow("TEST",img)
cv2.waitKey(0)
Solution Tried : sudo chmod -R 777 to targetfolder
but no change.
Closing and reopening the IDE didn’t help.
Rebooting the laptop didn’t help
Python Version: 3.8.5
opencv version: 4.4.0
Just checked the previous OpenCV versions. The issue persists on 4.3.0.38, but not on '4.3.0.36'. So whatever is causing it, started on that version.
I guess I continue using '4.3.0.36' for now...
Usually because you are referencing an object that no longer exists.
Are you realeasing the videocapture too early (if you are using it)
Or
Are you calling cv2.destroyallwindows() whithin your while loop?
Both of these, if inside your while loop, would cause the error.
If the above code is all you have so far...
Try
`import cv2
img = cv2.imread("MyFriends.jpg")
cv2.imshow("TEST",img)
cv2.waitKey(0)
cv2.destroyAllWindows()`

videowriter crashes when run using pyinstaller

For the past several weeks I have been using videowriter.write() and it has been working fine. I needed to give the program to several coworkers that have random python installations so I packaged it up in pyinstaller, which I have used successfully on other projects.
Almost everything seems to be working fine when run under pyinstaller, I can read images, capture images from the camera, show them on the screen, and write out individual images. The problem is that when I use videowriter.write() somewhere down in the bowels of the code it crashes, complaining that the images have the incorrect size. This only happens when running under pyinstaller, not when running it directly from python.
Below is a portion of the code that I extracted with a generated test image. A coworker tried to run the same example, using his copy of opencv, python, and pyinstaller and his executable seems to work. I spent the last several days trying to duplicate that setup but I don't get the same results. I have completely removed python 3 (I have a copy of 2.7 that is specifically for other tests), cleared the pip cache, cleared environment variables, and made sure all the python directories were removed prior to re-installation. I have tried python back to 3.7, different versions of opencv 4.1 through current, and all behave the same way. I have also tried using a virtual environment and setting up the core python sitting in Program Files.
The current version of opencv_videoio_ffmpeg is: opencv_videoio_ffmpeg420_64.dll.
The version that my coworker used successfully is opencv_ffmpeg410_64.dll
While it doesn't seem to make much difference, the command I have been using to build the executable is:
pyinstaller videowriter_test.py --onefile
I have also tried it without the --onefile option, it works the same but its a little harder to find the executable.
The python installation has the following installed: opencv-python, opencv-contrib-python, imutils, pynput, keyboard, virtualenv, pyinstaller. These were all installed using pip.
pyinstaller stats:
129 INFO: PyInstaller: 3.6
129 INFO: Python: 3.7.7
131 INFO: Platform: Windows-10-10.0.18362-SP0
133 INFO: wrote C:\Users\tbray\Desktop\MyProjects\Python3\Play\videowriter\videowriter_test.spec
137 INFO: UPX is not available. 139 INFO: Extending PYTHONPATH with paths
The test code:
import traceback
import cv2
import numpy as np
import imutils
# the rest are just there to make sure pyinstaller includes the same modules
# as my regular code
import copy
import platform
import pathlib
import select
import argparse
import warnings
import datetime
import json
import time
if __name__ == '__main__':
w = 640
h = 480
currentVideoLogFilename = "test.avi"
print(os.getenv('temppath'))
try:
print("Attempting to open Video Log:", currentVideoLogFilename)
video_log_file = cv2.VideoWriter(currentVideoLogFilename,
cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30, (w, h),True)
print("Open Success")
except:
traceback.print_exc()
print("Test Image Shape:", w, h)
image = np.zeros((w, h, 3))
try:
video_log_file.write(image)
except:
traceback.print_exc()
print("Completed")
video_log_file.release()
print("file closed/released")
sys.exit(0)
If I run the using idle or pyCharm, I get this result:
================== RESTART: C:\Users\tbray\Desktop\MyProjects\Python3\Play\videowriter\videowriter_test.py ==================
None
Attempting to open Video Log: test.avi
Open Success
Test Image Shape: 640 480
Completed
file closed/released
>>>
if I run it from the virtual environment I get:
C:\Users\tbray\Desktop\MyProjects\Python3\Play\videowriter\dist>videowriter_test.exe
None
Attempting to open Video Log: test.avi
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): test.avi in function 'cv::icvExtractPattern'
Open Success
Test Image Shape: 640 480
Traceback (most recent call last):
File "videowriter_test.py", line 39, in <module>
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_mjpeg_encoder.cpp:476: error: (-215:Assertion failed) imgWidth == frameWidth && imgHeight == frameHeight && channels == 3 in function 'cv::mjpeg::MotionJpegWriter::write'
Completed
file closed/released
One interesting note is what I assume is the temp directory that is referenced in the first error message. I have no idea where the directory comes from and what happens to it, it is missing when I go looking for it.
Any suggestions?

Running face_recognition model lead to "python has stopped working"

I tried running the following code:
import face_recognition
known_image = face_recognition.load_image_file("biden.jpg")
unknown_image = face_recognition.load_image_file("unknown.jpg")
biden_encoding = face_recognition.face_encodings(known_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
results = face_recognition.compare_faces([biden_encoding], unknown_encoding)
the known_image and unknown_image have the type numpy.ndarray and the values get loaded in it. But while calling the function face_recognition.face_encodings, the following message appears:
Python has stopped working. Kernel has been dead and restarted.
Can't figure out what's happening?
What are you jupyter, python versions?
Reason 1: Broken installation
Can you try uninstalling all of:
ipykernel
ipython
jupyter_client
jupyter_core
traitlets
ipython_genutils
More information here.
Reason 2: Data are huge, memory is not enough, kernel dies

Zlib and binascii don't build with Python3.6

I've been trying to build Python3.6.1 from source code on Ubuntu 14.04. The sequence of commands is as recommended by README:
./configure
make
make test
The latter crashes because it cannot import binascii. In its output there is a following:
Following modules built successfully but were removed because they could not be imported:
binascii zlib
Trying to skip make test and start make install I have it crashing after failing to import zlib. Some folks in the Ubuntu forums suggested to update all the zlib's packages from repositories. That doesn't help. How do I fix this?
Try to install zlib from the source code(http://www.zlib.net/) manually (not via yum/apt-get/brew...) might be helpful.
I have tried the Python3.6.1 building in my mac dev and also encountered your problem. It complains following message after making.
Python build finished successfully!
The necessary bits to build these optional modules were not found:
... zlib ...
And I can't import zlib in interactive shell too.
>>> import zlib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'zlib'
I have solved the problem by the following steps.
visit http://www.zlib.net/ and download zlib-1.2.11.
install zlib (decompress, configure, make, make install).
reinstall Python3.6.1 (make clean, make).
I found the making process did not complain about zlib missing anymore and I could import zlib successfully in the shell.
Actually, to solve this kind of problems, we might find some hints from the source code.
We can find the following code in "setup.py" and the comments are pretty helpful. We can modify the code with debug information to locate where the problem really is (for me, it is because the first if check fails due to zlib.h missing).
# You can upgrade zlib to version 1.1.4 yourself by going to
# http://www.gzip.org/zlib/
zlib_inc = find_file('zlib.h', [], inc_dirs)
have_zlib = False
if zlib_inc is not None:
zlib_h = zlib_inc[0] + '/zlib.h'
version = '"0.0.0"'
version_req = '"1.1.3"'
if host_platform == 'darwin' and is_macosx_sdk_path(zlib_h):
zlib_h = os.path.join(macosx_sdk_root(), zlib_h[1:])
with open(zlib_h) as fp:
while 1:
line = fp.readline()
if not line:
break
if line.startswith('#define ZLIB_VERSION'):
version = line.split()[2]
break
if version >= version_req:
if (self.compiler.find_library_file(lib_dirs, 'z')):
if host_platform == "darwin":
zlib_extra_link_args = ('-Wl,-search_paths_first',)
else:
zlib_extra_link_args = ()
exts.append( Extension('zlib', ['zlibmodule.c'],
libraries = ['z'],
extra_link_args = zlib_extra_link_args))
have_zlib = True
else:
missing.append('zlib')
else:
missing.append('zlib')
else:
missing.append('zlib')

Resources