How to Install PyOpenCV on Ubuntu - python

I'm trying to install PyOpenCV on Ubuntu 14.04 using setuptools. When I tried
python setup.py config
I got the error
ImportError: cannot import name Library
I found in an answer to a previous question that the fix was to change
from setuptools import Library
to
from setuptools.extension import Library
in setup.py. Now when I run setup.py, the error occurs in the config.py script it generates:
$ python setup.py config
Configuring PyOpenCV via CMake...
<snip>
-- Configuring done
-- Generating done
-- Build files have been written to: /home/saul/Downloads/pyopencv/build
Traceback (most recent call last):
File "setup.py", line 137, in <module>
import config as C
File "/home/saul/Downloads/pyopencv/config.py", line 1, in <module>
from setuptools import Extension, Library
ImportError: cannot import name Library
The first line of config.py contains the same import error. I can correct config.py of course, but I don't know how to resume the build process.
The text of setup.py from the point of failure is:
import config as C
setup(
name = "pyopencv",
version = C.PYOPENCV_VERSION,
description = DOCLINES[0],
author = 'Minh-Tri Pham',
author_email = 'pmtri80#gmail.com',
url = 'http://code.google.com/p/pyopencv/',
license = 'New BSD License',
platforms = 'OS Independent, Windows, Linux, MacOS',
classifiers = filter(None, CLASSIFIERS.split('\n')),
long_description = "\n".join(DOCLINES[2:]),
ext_modules=C.extension_list,
install_requires = ['numpy>=1.2.0'],
package_data = {'pyopencv': ['*.dll']},
include_package_data = True,
# zip_safe = (os.name!='nt'), # thanks to ffmpeg dependency
package_dir={'':'package'},
packages = find_packages('package'),
)
Can you tell me how to fix this, or suggest an alternative way to install pyOpenCV?

There is much simple way to do it, open terminal and type :
sudo apt-get install python-opencv

Related

Getting ModuleNotFoundError when trying to import third party modules in setup.py

I am currently writing a module and I want to use mypyc for it. I was following the documentation for using it inside setup.py but I am getting a ModuleNotFoundError everytime I try to import it there and run pip install ..
When running python setup.py install everything works without issue.
The error shows up when I try to import other modules too. They are all installed of course.
I have no idea what the problem could be.
This is my setup.py file:
from mypyc.build import mypycify
from setuptools import find_packages, setup
setup(
name="my_lib_name",
author="my_name",
url="my_url",
license="MIT",
description="Some description",
packages=find_packages(),
version="0.0.1",
install_requires=["levenshtein", "unidecode", "mypy"],
ext_modules=mypycify(["mylib/"]), # type: ignore
python_requires=">=3.9",
setup_requires=["pytest-runner"],
tests_require=["pytest"],
test_suite="tests",
)
And the error I am getting when running pip install .:
File "setup.py", line 1, in <module>
from mypyc.build import mypycify
ModuleNotFoundError: No module named 'mypyc'
----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\my_path\venv\scripts\python.exe' 'c:\users\my_path\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py' get_requires_for_build_wheel 'C:\Users\my_name\AppData\Local\Temp\tmpa7qmg4q1' Check the logs for full command output.
Again, when running python setup.py install I dont get any error.
And of course, when I remove the mypyc import everything also works as intended.
Not sure what I am doing wrong here, hope someone can help me out.
For completion, I am using Python Version 3.9.2 and pip Version 20.2.3, but this error is also there when using the latest pip Version 22.0.4.
After a lot of trial and error, I have found the culprit. I had a pyproject.toml file in my project which seemed to cause the issue for whatever reason?? I am not sure why, it interferes with it for some reason.
This was the content of that pyproject.toml file:
[tool.black]
line_length=88
[tool.isort]
profile="black"
I added these lines on the top:
[build-system]
requires = ["setuptools", "setuptools-scm", "mypy"]
build-backend = "setuptools.build_meta"
"mypy" being the package that I want to import in the setup.py file.
Deleting the file completely works, too.
I hope this will help someone, maybe.

How can I install a .so file generated from CMake and import it in python?

I tried these lines of code here in setup.py:
from distutils.core import setup
setup (name = 'package_name',
version = '0.1',
author = "Nobody",
description = """Install precompiled extension""",
packages=[''],
package_data={'': ['path_to_package/package_name.so']},
)
And running path/to/my/python -m pip install -e . will say the package is installed successfully.
However I got module not found error when I tried to import the package.
So, is it possible to install .so in pip? If so, how should I modify the setup.py file?
Thanks in advance!
I think this will help you: Building C and C++ Extensions
Edit:
Just forget my first answer, you just have to name your package. That is fill in the empty strings on line 6 and 7. And you have to add the directory containing the .so file AFTER the install to the PYTHONPATH environment variable.

How to create a shareable python distribution package that can be installed using pip?

I want to share my python code with my colleague in a way that he will get the distribution package and using pip the package can be installed on his/her machine.
I created .whl file which i thought can be directly installed through the pip install command.
Though it was installed successfully, when i start using it shows the error.
Is this possible like i give .whl file and it can be used in other's machine once installed through pip install command ?
I'm trying to do it on windows machine.
Here is the setup.py :
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='dokr',
version='0.1',
scripts=['dokr'] ,
author="Debapritam Chakra",
author_email="debapritam22#gmail.com",
description="A Sample package",
long_description=long_description,
long_description_content_type="text/markdown",
url="",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 2.7",
"",
"Operating System :: OS Independent",
],
)
package that i am trying to create is dokr and have file named dokr in the same directory which has the content shown below.
#!/usr/bin/env python
echo "hey there, this is a pip package"
used the command python setup.py sdist bdist_wheel to generate the distribution package.
To install package on my machine, I used the command :
python -m pip install dist/name-of-wheel-file.whl
It showed it is installed successfully(even checked using the pip list).
It throws the error when i try to import the package as
import dokr
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named dokr
Additional observation :
Python on my machine is installed under C:\Python27.
After installing the package from whl file using pip, I could see there is a directory created under the path : C:\Python27\Lib\site-packages\
named dokr-0.1.dist-info.For which pip list shows that the module is present.
But there is no such folder having the python file dokr itself, which i want to import in other python file. which shows error during importing.
I am new to python and this platform as well. Any lead would be helpful.
Ofcourse, you can create a python distribution package.
Can you clearly show what is the error?
However, you can look into the following link!
: Packaging Python Projects
Hope this helps!
Fortunately found the cause of the problem.
I did not pass the argument( packages which takes the list of packages to be included ) in the setup function, for which packages could not be copied.
Following article and an awesome answer helped to sort out the issue.
https://setuptools.readthedocs.io/en/latest/setuptools.html#developer-s-guide
pip install . creates only the dist-info not the package
And I thank everyone who came here to help. :)

setup.py: add dependencies required for installation [duplicate]

I'm developing a Python application and in the process of branching off a release. I've got a PyPI server set up on a company server and I've copied a source distribution of my package onto it.
I checked that the package was being hosted on the server and then tried installing it on my local development machine. I ended up with this output:
$ pip3 install --trusted-host 172.16.1.92 -i http://172.16.1.92:5001/simple/ <my-package>
Collecting <my-package>
Downloading http://172.16.1.92:5001/packages/<my-package>-0.2.0.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\setup.py", line 9, in <module>
import appdirs
ModuleNotFoundError: No module named 'appdirs'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\
The reason is that I'm trying to import a third-party library appdirs in my setup.py, which is necessary for me to compute the data_files argument to setup():
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os
from collections import defaultdict
import appdirs
from <my-package>.version import __version__ as <my-package>_version
APP_NAME = '<my-app>'
APP_AUTHOR = '<company>'
SYSTEM_COMPONENT_PLUGIN_DIR = os.path.join(appdirs.user_data_dir(APP_NAME, APP_AUTHOR), 'components')
# ...
setup(
# ...
data_files=component_files,
)
However, I don't have appdirs installed on my local dev machine and I don't expect the end users to have it either.
Is it acceptable to rely on third-party libraries like this in setup.py, and if so what is the recommended approach to using them? Is there a way I can ensure appdirs gets installed before it's imported in setup.py, or should I just document that appdirs is a required package to install my package?
I'm ignoring licensing issues in this answer. You definetly need to take these into account before you really do a release.
Is it acceptable to rely on third-party libraries like this in setup.py
Yes, it is acceptable but generally these should be minimized, especially if these are modules which have no obvious use for the end-user. Noone likes to have packages they don't need or use.
what is the recommended approach to using them?
There are basically 3 options:
Bootstrap them (for example use pip to programmatically install packages). For example setuptools provides an ez_setup.py file that can be used to bootstrap setuptools. Maybe that can be customized to download and install appdirs.
Include them (especially if it's a small package) in your project. For example appdirs is basically just a single file module. Pretty easy to copy and maintain in your project. Be very careful with licensing issues when you do that!
Fail gracefully when it's not possible to import them and let the user install them. For example:
try:
import appdirs
except ImportError:
raise ImportError('this package requires "appdirs" to be installed. '
'Install it first: "pip install appdirs".')
You could use pip to install the package programmatically if the import fails:
try:
import appdirs
except ImportError:
import pip
pip.main(['install', 'appdirs'])
import appdirs
In some circumstances you may need to use importlib or __import__ to import the package after pip.main or referesh the PATH variable. It could also be worthwhile to include a verification if the user really wants to install that package before installing it.
I used a lot of the examples from "Installing python module within code" and I haven't personally tried used this in setup.py files but it looks like it could be a solution for your question.
You can mention install_requires with the dependencies list. Please check the python packaging guide here. Also you can provide a requirements.txt file so that it can be run at once using "pip install -r"

Can't run Pygame script that plays a OGG file compiled through cx_Freeze

When I compile the following script:
# play.py
import os, re
import pygame.mixer
pygame.mixer.init(11025)
pygame.mixer.music.load('song.ogg')
pygame.mixer.music.play(-1)
os.system("PAUSE")
Using the following setup.py:
from cx_Freeze import setup, Executable
exe = Executable(
script="play.py",
)
setup(
executables = [exe]
)
Through:
python setup.py build
Executing play.exe gives me the following error:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 2
7, in <module>
exec(code, m.__dict__)
File "play.py", line 7, in <module>
pygame.error: Couldn't open 'song.ogg'
The script works fine before compiling and yes, I did put song.ogg in exe's directory. By the way song.ogg works fine, I already checked. Any ideas?
P.S. If I change it to song.wav it works fine, but WAV files are way too large for me to use. Also MP3 doesn't work as it should.
Through Process Explorer I was able to find out I needed to copy libogg.dll, libvorbis.dll and libvorbisfile.dll from Python33\Lib\site-packages\pygame to my frozen program's directory.
The computer cant open the song.ogg file because cx_freeze did not include the song in it's compiling. You should try including the song file into the setup.py script. Using a setup.py script like the one below.
from cx_Freeze import setup, Executable
exe=Executable(
script="play.py",
base="Win32Gui",
)
includefiles=[song.ogg]
includes=[]
excludes=[]
packages=[]
setup(
version = "0.0",
description = "Description",
author = "Name",
name = "Play",
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [exe]
)
Expanding on your answer, I found the this solution for mac users (assuming you used Homebrew to install pygame):
brew install libogg
brew install libvorbis
brew install sdl_mixer --with-libvorbis
If you receive a message saying "Warning: sol_mixer-1.2.12 already installed." after running the 3rd command, then replace it with the following:
brew reinstall sdl_mixer --with-libvorbis
For reference: can't open sound files using pygame on a mac

Categories