I am having trouble identifying what causes this problem. Basically, I am working on a jupyter notebook that runs on a conda environment.
I have created a file "Myutils.py" which has some helper function for later use. the file is saved in the same folder as the notebook.
Giving that I have made the necessary imports in the notebook as well as in the Myutils file, I still got a name error:
In notebook:
first cell:
import cv2
import pytesseract
import numpy as np
import os
import matplotlib.pyplot as plt
from MyUtils import *
%matplotlib inline
then:
img = cv2.imread('./yolov5/runs/detect/exp/crops/address/422.jpg')
plt.imshow(remove_noise(img))
produces this error message:
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17892/550149434.py in <module>
1 img = cv2.imread('./yolov5/runs/detect/exp/crops/address/422.jpg')
----> 2 plt.imshow(remove_noise(img))
~\Documents\Machine Learning\Projects\CIN OCR\MyUtils.py in remove_noise(image)
5 def get_grayscale(image):
6 return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
----> 7
8 # noise removal
9 def remove_noise(image):
NameError: name 'cv2' is not defined
And, in the Myutils.py, we have:
import cv2
import numpy as np
# get grayscale image
def get_grayscale(image):
return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
By doing from Myutils import * you are overriding the earlier import cv2.
I don't know if this is what is causing your bug, but it's worth avoiding import * unless you are certain there are no conflicts - see e.g:
Why is "import *" bad?
Related
As the title says, I'm encountering an issue where a function imported from a file (myfun_fromfile) doesn't seem to have access to other imported modules, e.g. cv2.
Solutions that work are 1) defining the function in the same script it's called in (myfun_inline) and 2) importing the module inside the function imported from file (myfun_fromfile_containsimport). I'd prefer to separate my function definitions and workflow, so 1 is not an ideal solution for me. And solution 2 seems... strange?
What's going on here? And how can I import a function from file and have it call modules successfully?
Example code
file functions.py that contains two functions, myfun_fromfile and myfun_fromfile_containsimport:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def myfun_fromfile(path_to_image):
img = cv2.imread(path_to_image, cv2.IMREAD_UNCHANGED)
return img
def myfun_fromfile_containsimport(path_to_image):
# the only difference is "import cv2"
import cv2
img = cv2.imread(path_to_image, cv2.IMREAD_UNCHANGED)
return img
main script:
# import module cv2 and two functions from functions.py
import cv2
from functions import (myfun_fromfile, myfun_fromfile_containsimport)
# define an inline function
def myfun_inline(path_to_image):
img = cv2.imread(path_to_image, cv2.IMREAD_UNCHANGED)
return img
#
path_to_image = '../data/train/5fb9edb4-bb99-11e8-b2b9-ac1f6b6435d0_red.png'
# compare from-file and inline directly
img1 = myfun_fromfile(path_to_image) # this does not work, see error below
img1 = myfun_inline(path_to_image) # this works, solution 1
img2 = myfun_fromfile_containsimport(path_to_image) # this works, solution 2
Error message thrown by myfun_fromfile
img1 = myfun_fromfile(path_to_image)
Traceback (most recent call last):
Cell In[385], line 1
img1 = myfun_fromfile(path_to_image)
File ~/path/to/functions.py:10 in myfun_fromfile
img = cv2.imread(path_to_image, cv2.IMREAD_UNCHANGED)
NameError: name 'cv2' is not defined
Adding the answer from Michael Butscher's comment:
Include the module imports in the external file. So in this, add import cv2 to the top of function.py, but not inside the function definitions.
When I run the code:
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
from typing import List, Tuple
import os
import scipy.io, scipy.signal
import colorednoise as cn
def generate_pink_noise(singal_length):
beta = 1
samples = singal_length
noise = cn.powerlaw_psd_gaussian(beta, samples)
return noise
I get:
Traceback (most recent call last):
File "...MEA_foward_model.py", line 11, in <module>
import colorednoise as cn
ModuleNotFoundError: No module named 'colorednoise'
Note the 'test' environment I'm using shown here when I get the error: environment.
However the same code runs without error in Jupiter notebook:
import colorednoise as cn
signal_length =10
beta = 1 # the exponent: 0=white noite; 1=pink noise; 2=red noise (also "brownian noise")
samples = signal_length # number of samples to generate (time series extension)
noise = cn.powerlaw_psd_gaussian(beta, samples)
This image shows (see top right corner) shows that the same environment is used
jupyter notebook output. What is causing this dissonance between the two different behaviours?
I am using Jupyter Lab for image processing and am trying to implement hough circle transform but I keep getting this error in my imports.
ImportError Traceback (most recent call last)
<ipython-input-4-695140ab07cc> in <module>
1 get_ipython().system('pip install impy')
----> 2 from impy import imarray
3 import numpy as np
4 import matplotlib.pyplot as plt
5 from scipy.ndimage import imread
ImportError: cannot import name 'imarray' from 'impy' (C:\Users\himad\anaconda3\lib\site-packages\impy.py)
I've looked up many solutions but none of them seem to work. Can someone help me out with this?
I am trying import a module in Jupyter and it is not working:
import alyn
ImportError Traceback (most recent call last)
<ipython-input-8-8e9535ea4303> in <module>()
----> 1 import alyn
~\Anaconda3\envs\tracx\lib\site-packages\alyn\__init__.py in <module>()
1 """ Import required modules"""
----> 2 from deskew import *
3 from skew_detect import *
ImportError: No module named 'deskew'
I don't quite understand why, since the package in question has a correct init.py file:
whose contents are:
""" Import required modules"""
from deskew import *
from skew_detect import *
What am I missing?
P.S.
This is all taking place on Windows 10.
Well, I've figured it out!
Turns out that the package I was trying to import is written in Python 2 and its init file is using the relative import mechanism. However, I am working in Python 3 and relative import is no longer supported in it. The init file can be made to work in Python 3 by adding a . in both lines, like this:
""" Import required modules"""
from .deskew import *
from .skew_detect import *
I think this should be backward compatible with Python 2.
The tutorial is on http://mxnet.io/tutorials/python/mnist.html.
At this step:
"
from IPython.display import HTML
import cv2
import numpy as np
from mnist_demo import html, script
def classify(img):
img = img[len('data:image/png;base64,'):].decode('base64')
img = cv2.imdecode(np.fromstring(img, np.uint8), -1)
img = cv2.resize(img[:,:,3], (28,28))
img = img.astype(np.float32).reshape((1,1,28,28))/255.0
return model.predict(img)[0].argmax()
'''
To see the model in action, run the demo notebook at
https://github.com/dmlc/mxnet-notebooks/blob/master/python/tutorials/mnist.ipynb.
'''
HTML(html + script)
"
ImportError Traceback (most recent call last)
in ()
2 import cv2
3 import numpy as np
----> 4 from mnist_demo import html, script
5 def classify(img):
6 img = img[len('data:image/png;base64,'):].decode('base64')
ImportError: No module named mnist_demo
I do not know what is the reason and I cannot find the answer on Google.
Does anyone has any idea?
That was because the tutorial was not written in a single file. You should put the mnist_demo.py file together with your the tutorial notebook. The file could be found at mxnet-notebooks on the github site.
:P