Ask Your Question
1

Corrupt/truncated output of `cv2.bitwise_and` -- fixed in OpenCV 2.4?

asked 2013-06-17 04:38:40 -0600

Intermittently, the output of "cv2.bitwise_and" (called from the python bindings) is wrong. It looks as if somehow the ANDing process was interrupted before it completed:

source_masked.png

source_masked.png

source.png:

source.png

mask.png:

mask.png

I can reproduce this almost every time on OpenCV 2.3, but not on 2.4 after thousands of runs. I have seen the same problem in the output of "cv2.matchTemplate" (square or triangular regions of output are missing, set to white or black instead). I have reproduced the problem on two different PCs.

My question is: Does anyone know of a fix in 2.4 that would have fixed this issue? I'm worried that maybe it's a race condition, and when I upgraded I changed the conditions slightly such that the race condition is no longer triggered, but is still latently present in 2.4.

I've searched the ticket tracker and the mailing list and the answers site, but didn't find anything relevant. There are several fixed issues relating to matchTemplate but all of them are GPU-related and I'm not using the GPU (as far as I know). I also searched the commit log and saw a commit that fixes "heap corruption in OutputArray::create" but I don't know if it is relevant.

On OpenCV 2.3, I can only reproduce this problem within my application that is taking frames from GStreamer. If I rerun the OpenCV processing on the same frames outside of my application, I can't reproduce the problem even after tens of thousands of runs; so I can't provide a minimal test case. And I can only reproduce it using the python bindings, not with C code.

My code is essentially this:

cv2.imwrite(
    "source.png",
    my_own_function_to_get_image_from_gstreamer())

source_masked = cv2.bitwise_and(
    cv2.imread("source.png"),
    numpy.array([255]),
    mask=cv2.imread("mask.png"))

cv2.imwrite(
    "source_masked.png",
    source_masked)
edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
0

answered 2013-06-19 05:00:14 -0600

This was an invalid use of the mask parameter. The mask parameter to bitwise_and means that the operation only changes those destination array pixels p for which mask(p) != 0. Since we're not specifying dst (destination), bitwise_and allocates a new output array, but doesn't initialize it properly, so anything in the output image in the area corresponding to the 0 pixels in the mask contain garbage, rather than 0. See http://code.opencv.org/issues/1748#note-2

The code above should be written as:

source_masked = cv2.bitwise_and(
    cv2.imread("source.png"),
    cv2.imread("mask.png"))

Presumably the reason I didn't see this behaviour in OpenCV 2.4.5 is because of http://code.opencv.org/issues/1286

edit flag offensive delete link more

Question Tools

Stats

Asked: 2013-06-17 04:38:40 -0600

Seen: 749 times

Last updated: Jun 19 '13