# Error installing specific version of OpenCV Python

**URL:** <https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427>\
**Category:** Python\
**Tags:** raspberrypi\
**Created:** [November 6, 2023, 1:44pm UTC](https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427 "2023-11-06T13:44:56Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![FordMontana](https://avatars.discourse-cdn.com/v4/letter/f/f08c70/32.png) [@FordMontana](https://forum.opencv.org/u/FordMontana)\
**Post date:** [November 6, 2023, 1:44pm UTC](https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427/1 "2023-11-06T13:44:57Z")

</div>

My OS is Raspberry Pi OS (Legacy) with desktop Bullseye 64 bit, python version is Python 3.9.2, and pip version is pip 23.3.1.

I am attempting to run this sample code in order to execute and test object detection with TensorFlow Lite. It instructs me to run the line below.

```auto
pip3 install opencv-python==4.4.0.46

```

However, I encounter the following error.

```auto
ERROR: Failed building wheel for opencv-python
Failed to build opencv-python
ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly

```

I then tried

```auto
pip install --upgrade pip setuptools wheel

```

But got the error

```auto
TypeError: _classify_installed_files() got an unexpected keyword argument 'cmake_install_dir'
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for opencv-python
Failed to build opencv-python
ERROR: Could not build wheels for opencv-python, which is required to install pyproject.toml-based projects

```

I tried to run

```auto
sudo pip install opencv-python==4.4.0.46

```

with error

```auto
ERROR: Failed building wheel for opencv-python
Failed to build opencv-python
ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly

```

I am attempting to run this sample code in order to execute and test object detection with TensorFlow Lite. With the code and instructions given below.

```auto
#!/usr/bin/python3

# Copyright (c) 2022 Raspberry Pi Ltd
# Author: Alasdair Allan <alasdair@raspberrypi.com>
# SPDX-License-Identifier: BSD-3-Clause

# A TensorFlow Lite example for Picamera2 on Raspberry Pi OS Bullseye
#
# Install necessary dependences before starting,
#
# $ sudo apt update
# $ sudo apt install build-essential
# $ sudo apt install libatlas-base-dev
# $ sudo apt install python3-pip
# $ pip3 install tflite-runtime
# $ pip3 install opencv-python==4.4.0.46
# $ pip3 install pillow
# $ pip3 install numpy
#
# and run from the command line,
#
# $ python3 real_time_with_labels.py --model mobilenet_v2.tflite --label coco_labels.txt

import argparse

import cv2
import numpy as np
import tflite_runtime.interpreter as tflite

from picamera2 import MappedArray, Picamera2, Preview

normalSize = (640, 480)
lowresSize = (320, 240)

rectangles = []

def ReadLabelFile(file_path):
    with open(file_path, 'r') as f:
        lines = f.readlines()
    ret = {}
    for line in lines:
        pair = line.strip().split(maxsplit=1)
        ret[int(pair[0])] = pair[1].strip()
    return ret

def DrawRectangles(request):
    with MappedArray(request, "main") as m:
        for rect in rectangles:
            print(rect)
            rect_start = (int(rect[0] * 2) - 5, int(rect[1] * 2) - 5)
            rect_end = (int(rect[2] * 2) + 5, int(rect[3] * 2) + 5)
            cv2.rectangle(m.array, rect_start, rect_end, (0, 255, 0, 0))
            if len(rect) == 5:
                text = rect[4]
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(m.array, text, (int(rect[0] * 2) + 10, int(rect[1] * 2) + 10),
                            font, 1, (255, 255, 255), 2, cv2.LINE_AA)

def InferenceTensorFlow(image, model, output, label=None):
    global rectangles

    if label:
        labels = ReadLabelFile(label)
    else:
        labels = None

    interpreter = tflite.Interpreter(model_path=model, num_threads=4)
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()
    height = input_details[0]['shape'][1]
    width = input_details[0]['shape'][2]
    floating_model = False
    if input_details[0]['dtype'] == np.float32:
        floating_model = True

    rgb = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
    initial_h, initial_w, channels = rgb.shape

    picture = cv2.resize(rgb, (width, height))

    input_data = np.expand_dims(picture, axis=0)
    if floating_model:
        input_data = (np.float32(input_data) - 127.5) / 127.5

    interpreter.set_tensor(input_details[0]['index'], input_data)

    interpreter.invoke()

    detected_boxes = interpreter.get_tensor(output_details[0]['index'])
    detected_classes = interpreter.get_tensor(output_details[1]['index'])
    detected_scores = interpreter.get_tensor(output_details[2]['index'])
    num_boxes = interpreter.get_tensor(output_details[3]['index'])

    rectangles = []
    for i in range(int(num_boxes)):
        top, left, bottom, right = detected_boxes[0][i]
        classId = int(detected_classes[0][i])
        score = detected_scores[0][i]
        if score > 0.5:
            xmin = left * initial_w
            ymin = bottom * initial_h
            xmax = right * initial_w
            ymax = top * initial_h
            box = [xmin, ymin, xmax, ymax]
            rectangles.append(box)
            if labels:
                print(labels[classId], 'score = ', score)
                rectangles[-1].append(labels[classId])
            else:
                print('score = ', score)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--model', help='Path of the detection model.', required=True)
    parser.add_argument('--label', help='Path of the labels file.')
    parser.add_argument('--output', help='File path of the output image.')
    args = parser.parse_args()

    if (args.output):
        output_file = args.output
    else:
        output_file = 'out.jpg'

    if (args.label):
        label_file = args.label
    else:
        label_file = None

    picam2 = Picamera2()
    picam2.start_preview(Preview.QTGL)
    config = picam2.create_preview_configuration(main={"size": normalSize},
                                                 lores={"size": lowresSize, "format": "YUV420"})
    picam2.configure(config)

    stride = picam2.stream_configuration("lores")["stride"]
    picam2.post_callback = DrawRectangles

    picam2.start()

    while True:
        buffer = picam2.capture_buffer("lores")
        grey = buffer[:stride * lowresSize[1]].reshape((lowresSize[1], stride))
        _ = InferenceTensorFlow(grey, args.model, output_file, label_file)

if __name__ == ' __main__':
    main()

```

I have been looking through google with no luck, and am asking as many forums as I can in hopes of finding a solution. Help would be greatly appreciated!

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [November 6, 2023, 1:52pm UTC](https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427/2 "2023-11-06T13:52:07Z")

</div>

> [@FordMontana](#):
>
> `pip3 install opencv-python==4.4.0.46`

i’m sure you can use almost _any_ opencv version here:

> [@FordMontana](#):
>
> `pip3 install opencv-python`

---

<div class="post-metadata">

**Author:** ![FordMontana](https://avatars.discourse-cdn.com/v4/letter/f/f08c70/32.png) [@FordMontana](https://forum.opencv.org/u/FordMontana)\
**Post date:** [November 6, 2023, 2:08pm UTC](https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427/3 "2023-11-06T14:08:25Z")

</div>

> [@FordMontana](#):
>
> `python3 real_time_with_labels.py --model mobilenet_v2.tflite --label coco_labels.txt`

I installed opencv with the command you suggested but when I attempt to run the script I get the error

```auto
FordMontana@raspberrypi:~ $ python3 real_time_with_labels.py --model mobilenet_v2.tflite --label coco_labels.txt
[2:38:34.723235530] [8518] INFO Camera camera_manager.cpp:297 libcamera v0.0.5+83-bde9b04f
[2:38:34.764116179] [8519] WARN RPI vc4.cpp:383 Mismatch between Unicam and CamHelper for embedded data usage!
[2:38:34.764928925] [8519] INFO RPI vc4.cpp:437 Registered camera /base/soc/i2c0mux/i2c@1/imx219@10 to Unicam device /dev/media1 and ISP device /dev/media2
[2:38:34.764984757] [8519] INFO RPI pipeline_base.cpp:1101 Using configuration file '/usr/share/libcamera/pipeline/rpi/vc4/rpi_apps.yaml'
QObject::moveToThread: Current thread (0x7fa0020c40) is not the object's thread (0x7fa0196680).
Cannot move to target thread (0x7fa0020c40)

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/home/FordMontana/.local/lib/python3.9/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: xcb, eglfs, linuxfb, minimal, minimalegl, offscreen, vnc.

Aborted

```

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [November 6, 2023, 3:02pm UTC](https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427/5 "2023-11-06T15:02:01Z")

</div>

hard to say, if the qt errors are from opencv or from the Preview.QTGL used there.

can you try with a more simple example prog, like [https://github.com/raspberrypi/picamera2/blob/main/examples/opencv\_face\_detect.py](https://github.com/raspberrypi/picamera2/blob/main/examples/opencv_face_detect.py) ?

---

<div class="post-metadata">

**Author:** ![FordMontana](https://avatars.discourse-cdn.com/v4/letter/f/f08c70/32.png) [@FordMontana](https://forum.opencv.org/u/FordMontana)\
**Post date:** [November 6, 2023, 3:31pm UTC](https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427/7 "2023-11-06T15:31:19Z")

</div>

I did manage to run this script without a problem

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [November 6, 2023, 3:46pm UTC](https://forum.opencv.org/t/error-installing-specific-version-of-opencv-python/15427/8 "2023-11-06T15:46:22Z")

</div>

> <https://github.com/raspberrypi/picamera2/issues/789>
>
> \*\*Please only ask one question per issue!\*\*
> 
> \*\*Describe what it is that you wa…nt to accomplish\*\*
> The error message contains the string:
> \`This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.\`
> 
> Which application should be re-installed?
> 
> \*\*Describe alternatives you've considered\*\*
> Running the following script from \[The Picamera2 Library\](https://datasheets.raspberrypi.com/camera/picamera2-manual.pdf) page 7 documentation:
> 
> \`\`\`
> from picamera2 import Picamera2, Preview
> import time
> picam2 = Picamera2()
> camera\_config = picam2.create\_preview\_configuration()
> picam2.configure(camera\_config)
> picam2.start\_preview(Preview.QTGL)
> picam2.start()
> time.sleep(2)
> picam2.capture\_file("test.jpg")
> \`\`\`
> \*\*Preview.DRM\*\* had more errors.
> 
> \*\*Additional context\*\*
> Add any other context or screenshots about the request here.
> \`\`\`
> $ sudo apt install python3-v4l2
> Reading package lists... Done
> Building dependency tree... Done
> Reading state information... Done
> python3-v4l2 is already the newest version (0.3.2-1).
> python3-v4l2 set to manually installed.
> 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
> \`\`\`
> There is no pip3 installed v4l2 package as shown below:
> 
> \`\`\`
> user@raspberrypi:~/.local/lib/python3.9/site-packages $ ls
> ljpegCompress.cpython-39-arm-linux-gnueabihf.so piexif
> numpy piexif-1.1.3.dist-info
> numpy-1.23.1.dist-info \_\_pycache\_\_
> OpenGL PyOpenGL-3.1.6.dist-info
> pidng simplejpeg
> pidng-4.0.9.dist-info simplejpeg-1.6.4.dist-info
> $ uname -a
> Linux raspberrypi 6.1.21+ #1642 Mon Apr 3 17:19:14 BST 2023 armv6l GNU/Linux
> $
> OS: Raspbian GNU/Linux 11 (bullseye) armv6l
> Host: Raspberry Pi Model B Plus Rev 1.2
> \`\`\`
> \_Glamor\_ is enabled; required to run \_libcamera-hello\_ successfully.
> 
> With \*\*Preview.QTGL\*\* the following output is displayed:
> \`\`\`
> $ python3 ./camera\_test.py
> \[11:36:33.147519858\] \[31060\] INFO Camera camera\_manager.cpp:297 libcamera v0.0.5+83-bde9b04f
> \[11:36:33.370927893\] \[31061\] INFO RPI vc4.cpp:437 Registered camera /base/soc/i2c0mux/i2c@1/ov5647@36 to Unicam device /dev/media3 and ISP device /dev/media0
> \[11:36:33.373569846\] \[31061\] INFO RPI pipeline\_base.cpp:1101 Using configuration file '/usr/share/libcamera/pipeline/rpi/vc4/rpi\_apps.yaml'
> \[11:36:33.472279094\] \[31060\] INFO Camera camera.cpp:1033 configuring streams: (0) 640x480-XBGR8888 (1) 640x480-SGBRG10\_CSI2P
> \[11:36:33.476899012\] \[31061\] INFO RPI vc4.cpp:565 Sensor: /base/soc/i2c0mux/i2c@1/ov5647@36 - Selected sensor format: 640x480-SGBRG10\_1X10 - Selected unicam format: 640x480-pGAA
> qt.qpa.xcb: could not connect to display 
> qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
> This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
> 
> Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, xcb.
> 
> Aborted
> \`\`\`
> 
> Thanks!
