Repository: opencv
Issue: JPEG2000 encoding/decoding fails when running in multiprocessing pool
Labels: bug,category: imgproc

### System Information

Python version: 3.10.6
OpenCV Python version: 4.6.0.66
Operating System / Platform: Windows 11

### Detailed description

When rapidly encoding and decoding images using the `cv.imencode(".jp2")` Python method inside a multiprocessing pool, the resulting image is somehow corrupted, as calls to `cv.imdecode(buffer)` log several errors in a non-deterministic way.
The kind of error depends on the images that are used.

For instance, when using the [CIFAR-10 dataset](https://github.com/YoongiKim/CIFAR-10-images), this is the error that is reported:
```
[ERROR:0@0.076] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp (299) cv::`anonymous-namespace'::errorLogCallback OpenJPEG2000: Expected a SOC marker 
```

Other images from different sources produce other errors. For instance, another image produces this error log:
```
[ERROR:0@0.860] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp (299) cv::`anonymous-namespace'::errorLogCallback OpenJPEG2000: Tile part length size inconsistent with stream length

[ERROR:0@0.864] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp (299) cv::`anonymous-namespace'::errorLogCallback OpenJPEG2000: Failed to decode the codestream in the JP2 file

imdecode_(''): can't read data: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp:592: error: (-2:Unspecified error) OpenJPEG2000: Decoding is failed in function 'cv::detail::Jpeg2KOpjDecoderBase::readData'

[ERROR:0@5.532] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp (299) cv::`anonymous-namespace'::errorLogCallback OpenJPEG2000: Stream too short, expected SOT

[ERROR:0@5.537] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp (299) cv::`anonymous-namespace'::errorLogCallback OpenJPEG2000: Failed to decode tile 1/1

[ERROR:0@5.541] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp (299) cv::`anonymous-namespace'::errorLogCallback OpenJPEG2000: Failed to decode the codestream in the JP2 file

imdecode_(''): can't read data: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\grfmt_jpeg2000_openjpeg.cpp:592: error: (-2:Unspecified error) OpenJPEG2000: Decoding is failed in function 'cv::detail::Jpeg2KOpjDecoderBase::readData'
```

The image which produces this comes from the [FRGC Morphs dataset](https://zenodo.org/record/4415270) (in particular `FRGC-Morphs\morph_facemorpher\04482d96.jpg_04493d86.jpg.jpg`).

Also, this issue isn't present (or at least no errors are printed) when not calling `cv.imdecode(buffer)` or not using the multiprocessing pool.

### Steps to reproduce

```py
from pathlib import Path
import multiprocessing as mp
import cv2 as cv


USE_MP = True
USE_DECODE = True


def process_image(path):
    image = cv.imread(str(path))
    for q in range(1000):
        try:
            success, encoded = cv.imencode(".jp2", image, [cv.IMWRITE_JPEG2000_COMPRESSION_X1000, q])
        except cv.error as e:
            raise RuntimeError(f"Failed to encode {path} with quality {q}") from e
        if not success or encoded is None:
            raise RuntimeError(f"Failed to encode {path} with quality {q}")
        if USE_DECODE:
            try:
                decoded = cv.imdecode(encoded, cv.IMREAD_UNCHANGED)
            except cv.error as e:
                raise RuntimeError(f"Failed to decode {path} with quality {q}") from e
            if decoded is None:
                raise RuntimeError(f"Failed to decode {path} with quality {q}")


if __name__ == "__main__":
    # all_files = list(Path("CIFAR-10-images-master").rglob("*.jpg"))
    all_files = [Path("FRGC-Morphs/morph_facemorpher/04482d96.jpg_04493d86.jpg.jpg")] * 100
    print(f"Processing {len(all_files)} files...")
    if USE_MP:
        with mp.Pool(processes=None) as pool:
            pool.map(process_image, all_files)
    else:
        for path in all_files:
            process_image(path)
```

Run this piece of code (you may need to change the `all_files` variable accordingly; the important thing is that more than one worker must be busy, preferably all); the console should report the mentioned OpenCV errors.

### Issue submission checklist

- [X] I report the issue, it's not a question
- [X] I checked the problem with documentation, FAQ, open issues, forum.opencv.org, Stack Overflow, etc and have not found any solution
- [X] I updated to the latest OpenCV version and the issue is still there
- [X] There is reproducer code and related data files (videos, images, onnx, etc)