Skip to content

Segmentation fault when camera is released after disabling RGB conversion #13697

Closed

Description

@jveitchmichaelis
System information (version)
  • OpenCV => Tested on 4.0.0 and 4.0.1
  • Operating System / Platform => Linux 4.14.79-v7+ armv7l (Pi 3B+)
  • Compiler => gcc
Detailed description

Capturing images from a camera on a Pi 3 B+. OpenCV is being run from within a Docker container, so the environment is reasonably clean. I have also replicated this when OpenCV is run on the Pi normally.

If I open the camera and capture an image, no problems. If I attempt to modify the camera settings, I can still capture images, but when the program quits (or in this case I manually release the camera), it segfaults.

gdb gets as far as releasing the V4L buffer and then dies:

(gdb) bt full
#0  __GI___libc_free (mem=0x6e80c008) at malloc.c:2966
        ar_ptr = <optimized out>
        p = <optimized out>
        hook = 0x0
#1  0x75d58e04 in cv::CvCaptureCAM_V4L::releaseBuffers (this=0x5d3e8) at /code/opencv/modules/videoio/src/cap_v4l.cpp:1870
No locals.
#2  0x75d53050 in cv::CvCaptureCAM_V4L::~CvCaptureCAM_V4L (this=0x5d3e8, __in_chrg=<optimized out>)
    at /code/opencv/modules/videoio/src/cap_v4l.cpp:371
No locals.
#3  0x75d530b4 in cv::CvCaptureCAM_V4L::~CvCaptureCAM_V4L (this=0x5d3e8, __in_chrg=<optimized out>)
    at /code/opencv/modules/videoio/src/cap_v4l.cpp:374
No locals.
#4  0x75d2a47c in cvReleaseCapture (pcapture=0x7efffb88) at /code/opencv/modules/videoio/src/videoio_c.cpp:115
No locals.
#5  0x75d2b23c in cv::DefaultDeleter<CvCapture>::operator() (this=0x60074, obj=0x5d3e8)
    at /code/opencv/modules/videoio/src/cap.cpp:49
No locals.
#6  0x75d2e9d8 in std::_Sp_counted_deleter<CvCapture*, cv::DefaultDeleter<CvCapture>, std::allocator<void>, (__gnu_cxx::_Lock_policy)1>::_M_dispose (this=0x60050) at /usr/include/c++/6/bits/shared_ptr_base.h:464
No locals.
#7  0x76c37ac8 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)1>::_M_release (this=0x60050)
    at /usr/include/c++/6/bits/shared_ptr_base.h:150
No locals.
#8  0x76c2fcc0 in std::__shared_count<(__gnu_cxx::_Lock_policy)1>::~__shared_count (this=0x7efffbe4, __in_chrg=<optimized out>)
    at /usr/include/c++/6/bits/shared_ptr_base.h:662
No locals.
#9  0x75d2b28c in std::__shared_ptr<CvCapture, (__gnu_cxx::_Lock_policy)1>::~__shared_ptr (this=0x7efffbe0,
    __in_chrg=<optimized out>) at /usr/include/c++/6/bits/shared_ptr_base.h:928
No locals.
#10 0x75d2d4f4 in std::__shared_ptr<CvCapture, (__gnu_cxx::_Lock_policy)1>::reset (this=0x7efffc54)
    at /usr/include/c++/6/bits/shared_ptr_base.h:1025
No locals.
#11 0x75d2d184 in cv::Ptr<CvCapture>::release (this=0x7efffc54)
---Type <return> to continue, or q <return> to quit---
    at /code/opencv/modules/core/include/opencv2/core/cvstd_wrapper.hpp:121
No locals.
#12 0x75d2bca8 in cv::VideoCapture::release (this=0x7efffc50) at /code/opencv/modules/videoio/src/cap.cpp:171
        __cv_trace_location_extra_fn169 = 0x0
        __cv_trace_location_fn169 = {ppExtra = 0x75d7bf00 <cv::VideoCapture::release()::__cv_trace_location_extra_fn169>,
          name = 0x75d62388 <cv::VideoCapture::release()::__PRETTY_FUNCTION__> "virtual void cv::VideoCapture::release()",
          filename = 0x75d61ff8 "/code/opencv/modules/videoio/src/cap.cpp", line = 169, flags = 1}
        __PRETTY_FUNCTION__ = "virtual void cv::VideoCapture::release()"
        __region_fn = {pImpl = 0x0, implFlags = 0}
#13 0x000117b0 in main () at test_camera.cpp:18
        cap = {_vptr.VideoCapture = 0x75d7ac28 <vtable for cv::VideoCapture+8>,
          cap = {<std::shared_ptr<CvCapture>> = std::shared_ptr (empty) 0x0, <No data fields>},
          icap = {<std::shared_ptr<cv::IVideoCapture>> = std::shared_ptr (empty) 0x0, <No data fields>}}
        image = {flags = 1124024322, dims = 2, rows = 512, cols = 640,
          data = 0x6e67a040 "\326P\306P\320P\315P\317P\337P\327P\327P\334P\320P\342P\331P\341P\341P\304P\313P\330P\310P\327P\326P\332P\330P\353P\355P\361P\335P\323P\323P\327P\335P\322P\335P\341P\323P\314P\322P\320P\310P\347P\345P\343P\347P\324P\333P\355P\361P\344P\331P\340P\334P\347P\345P\310P\325P\322P\322P\316P\332P\332P\334P\333P\340P\335P\336P\310P\307P\344P\330P\333P\335P\353P\351P\361P\325P\354P\356P\354P\327P\342P\331P\320P\330P\335P\317P\331P\321P\343P\337P\336P\330P\332P\333P\342P\335P\334P\330P\317P\333P\306P\306P"...,
          datastart = 0x6e67a040 "\326P\306P\320P\315P\317P\337P\327P\327P\334P\320P\342P\331P\341P\341P\304P\313P\330P\310P\327P\326P\332P\330P\353P\355P\361P\335P\323P\323P\327P\335P\322P\335P\341P\323P\314P\322P\320P\310P\347P\345P\343P\347P\324P\333P\355P\361P\344P\331P\340P\334P\347P\345P\310P\325P\322P\322P\316P\332P\332P\334P\333P\340P\335P\336P\310P\307P\344P\330P\333P\335P\353P\351P\361P\325P\354P\356P\354P\327P\342P\331P\320P\330P\335P\317P\331P\321P\343P\337P\336P\330P\332P\333P\342P\335P\334P\330P\317P\333P\306P\306P"..., dataend = 0x6e71a040 "", datalimit = 0x6e71a040 "", allocator = 0x0, u = 0x4c850, size = {p = 0x7efffc20},
          step = {p = 0x7efffc48, buf = {1280, 2}}}
        res = true

This triggers specifically on operations where the buffer size changes. If I change the fourcc code to Y16, but I don't disable RGB conversion then the code doesn't error because it's still returning the correct size array. Disabling RGB conversion on its own is enough to trigger it as the camera delivers grayscale images normally.

If I open the camera, change the settings, but don't capture an image, the camera releases correctly. As soon as an image with a different buffer size is captured, things fail.

I thought it may be an issue with version 4 specifically. When I built 3.40/5 I get an error that neither of the properties were valid for the camera which is also weird because clearly they are and it was working before.

Without using Docker, the code works in C++ but not in Python.

This error doesn't occur on x86_64 Linux or Windows, so I'll try on a clean Raspberry Pi image next.

Steps to reproduce

Dockerfile for code generation - should be easy to replicate:

FROM raspbian/stretch as pi_opencv

WORKDIR /dev

RUN apt-get update && apt-get -y upgrade
RUN apt-get install -y build-essential git pkg-config cmake unzip

# Get OpenCV repo

RUN git clone https://github.com/opencv/opencv.git
RUN git clone https://github.com/opencv/opencv_contrib.git

# Get Python

RUN apt-get update && apt-get install -y python3 python3-dbg python3-pip python3-dev gfortran libatlas-base-dev libeigen3-dev
RUN pip3 install setuptools
RUN pip3 install numpy
RUN pip3 install scipy
RUN pip3 install scikit-learn
RUN pip3 install ipython

# Get OpenCV dependencies

RUN apt-get install -y libjpeg-dev libpng-dev libtiff-dev
RUN apt-get install -y libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
RUN apt-get install -y libgstreamer1.0-0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav gstreamer1.0-doc gstreamer1.0-tools
RUN apt-get install -y libxvidcore-dev libx264-dev
RUN apt-get install -y gfortran libatlas-dev libeigen3-dev liblapack-dev
RUN apt-get install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
RUN apt-get install -y libgtk-3-dev libcanberra-gtk*

RUN cd opencv && git checkout 4.0.1
RUN cd opencv_contrib && git checkout 4.0.1

# Install OpenCV
RUN cd opencv && mkdir build && cd build && cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH= opencv_contrib/modules \
    -D ENABLE_NEON=ON \
    -D ENABLE_VFPV3=ON \
    -D BUILD_TESTS=OFF \
    -D BUILD_JAVA=OFF \
    -D BUILD_PERF_TESTS=OFF \
    -D ENABLE_PRECOMPILED_HEADERS=OFF \
    -D INSTALL_PYTHON_EXAMPLES=OFF \
    -D BUILD_EXAMPLES=OFF \
    -D WITH_V4L=ON \
    -D WITH_LIBV4L=ON \
    -D WITH_GSTREAMER=ON \
    -DCMAKE_BUILD_TYPE=Debug \
    -D OPENCV_GENERATE_PKGCONFIG=ON \
    ..

RUN cd opencv/build && make -j2 install
RUN ln -s /usr/local/python/cv2/python-3.5/cv2.cpython-35m-arm-linux-gnueabihf.so /usr/local/lib/python3.5/dist-packages/cv2.so
RUN ldconfig

Code that segfaults:

#include<opencv2/opencv.hpp>
#include<iostream>

int main(void){

   using namespace cv;

   auto cap = VideoCapture(0 + CAP_V4L2);

   cap.set(CAP_PROP_FOURCC, VideoWriter::fourcc('Y', '1', '6', ' '));
   cap.set(CAP_PROP_CONVERT_RGB, false);

   Mat image;
   bool res = cap.read(image);

   if(res) std::cout << "Took image" << std::endl;

   cap.release();
}

Compiled with:

g++ test_camera.cpp  `pkg-config --cflags --libs opencv4` -std=c++14 -g

Example Python output:

>>> import cv2
>>> cap = cv2.VideoCapture(0 + cv2.CAP_V4L2)
>>> cap.set(cv2.CAP_PROP_CONVERT_RGB, False)
True
>>> cap.release()
>>> cap = cv2.VideoCapture(0 + cv2.CAP_V4L2)
>>> cap.set(cv2.CAP_PROP_CONVERT_RGB, False)
True
>>> cap.read()
(True, array([[145, 141, 143, ..., 122, 134, 132],
       [143, 147, 144, ..., 128, 132, 141],
       [142, 147, 153, ..., 130, 133, 135],
       ...,
       [128, 128, 128, ..., 128, 128, 128],
       [128, 128, 128, ..., 128, 128, 128],
       [128, 128, 128, ..., 128, 128, 128]], dtype=uint8))
>>> cap.release()
*** Error in `python3': double free or corruption (!prev): 0x00e21228 ***
Aborted (core dumped)
>>> cap = cv2.VideoCapture(0 + cv2.CAP_V4L2)
>>> cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc(*"Y16 "))
True
>>> cap.set(cv2.CAP_PROP_CONVERT_RGB, False)
True
>>> cap.read()
(True, array([[20691, 20680, 20680, ..., 20612, 20651, 20654],
       [20669, 20682, 20698, ..., 20632, 20632, 20657],
       [20662, 20682, 20700, ..., 20626, 20636, 20656],
       ...,
       [20660, 20653, 20678, ..., 20624, 20624, 20649],
       [20656, 20648, 20671, ..., 20617, 20632, 20642],
       [20660, 20679, 20666, ..., 20642, 20636, 20652]], dtype=uint16))
>>> cap.set(cv2.CAP_PROP_CONVERT_RGB, True)
True
>>> cap.read()
Segmentation fault (core dumped)

Activity

  1. changed the title [-]Segmentation fault when camera is released after disabling RGB conversion[/-] [+]Segmentation fault when camera is released after disabling RGB conversion (within Docker)[/+] on Jan 26, 2019
  2. jveitchmichaelis commented on Jan 27, 2019

    @jveitchmichaelis
    ContributorAuthor

    This seems to be fixed with a similar solution as: tensorflow/tensorflow#7960, also see tensorflow/tensorflow#6968. Though their conclusion was that it was likely a bug in Python (or at least due to Numpy), whereas I see this in C++ too.

    Within the container, I installed libtcmalloc:

    sudo apt-get install libtcmalloc-minimal4
    export LD_PRELOAD="/usr/lib/libtcmalloc_minimal.so.4"

    And the problem disappears.

    I'll check if this occurs with a new base image (balenalib/raspberrypi3:stretch-build) without needing to resort to the above. EDIT: And no, it still happens. Summary:

    Pi + Python 3: fails
    Pi + C++: works
    Docker + Python, C++: fails
    Docker + Python, C++ with tcmalloc: works

  3. changed the title [-]Segmentation fault when camera is released after disabling RGB conversion (within Docker)[/-] [+]Segmentation fault when camera is released after disabling RGB conversion[/+] on Jan 27, 2019
  4. jveitchmichaelis commented on Mar 10, 2019

    @jveitchmichaelis
    ContributorAuthor

    I've now also run into this using opencv-python-headless on Ubuntu 18.04 (amd64). The same LD_PRELOAD trick fixes it.

    I'm curious to see if this is an error with this particular camera (a FLIR Boson). I'll see if I can get hold of something else to test with.

  5. jveitchmichaelis commented on Mar 11, 2019

    @jveitchmichaelis
    ContributorAuthor

    @alalek I think it's not restricted to ARM, as it also occurs on my AMD64 desktop:

    Operating System / Platform => Linux 4.15.0-46-generic x86_64
    Compiler => gcc7

    Exactly the same issue so I would relabel platform: linux. From some experimenting, I now think this is likely a bug in the V4L capture backend (something isn't being freed properly). Support was added here: #7293 but I don't know what cameras were used to test it, @Algomorph any thoughts?

    Aside

    Changing to tcmalloc introduces other errors. I have a test suite which runs two modules. One which acquires video, the other which does saves some images (the only 2 calls to OpenCV are imwrite).

    If I run the test suite for the camera with the libtcmalloc fix, all good. Similarly if I run the test suite for the other module, on its own, no problems. However if I run the full suite, the camera acquisition is fine, but the other module segfaults. Huh?

    The offending call is a 16-bit imwrite. If I change it to 8-bit, then everything is fine.

    def _write_tiff(self, filename, data):
            cv2.imwrite(filename, data.astype("uint16"))
    > segfault
    
    def _write_tiff(self, filename, data):
            data = data.astype("uint16")
            cv2.imwrite(filename, data)
    > bus error
    
    def _write_tiff(self, filename, data):
            #cv2.imwrite(filename, data.astype("uint16"))
            np.save(filename, data.astype('uint16'))
    > segfault
    
    def _write_tiff(self, filename, data):
            #cv2.imwrite(filename, data.astype("uint16"))
            np.save(filename, data) # Data is float
    > no issue
    

    So I guess tcmalloc breaks numpy in some weird way, but only in conjunction with video capture.

    Going forward

    I'll do some debugging in CAP_V4L and see if it's something obvious. I would imagine that the number of people capturing Y16 video without using a manufacturer SDK is quite low... I might also be able to use a gstreamer pipeline. I've been able to stream video using gstreamer without crashing, so while gstreamer also uses v4lsrc, it would at least isolate the error to CAP_V4L if CAP_GSTREAMER works.

    Update:

    I tried rebuilding OpenCV from scratch to be sure. I can open and close the following pipeline successfully:

    cv2.VideoCapture('v4l2src ! video/x-raw,format=GRAY16_LE, width=640, height=512 ! videoconvert ! appsink', cv2.CAP_GSTREAMER)
    

    It just doesn't return 16-bit images (not supported by the looks of it). So I think that rules out a bug in video4linux, because it's using it as a capture source.

    I'm going to have a go at:

    1) Seeing if I can track down/fix the bug in CAP_V4L

    2) Adding 16-bit support to CAP_GSTREAMER.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcategory: videoio(camera)platform: armpriority: low

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions