ImportError: cannot import name 'imresize' from 'scipy'? - python

I am using scipy but getting this error again and again. I used PILLOW and still got the same error.
This is my code
import cv2
import imutils
import numpy as np
from sklearn.metrics import pairwise
from keras.models import load_model
from scipy import imresize
import PIL
#from PIL import Imageresize as imresize
#from skimage.transform import resize
def getPredictedClass(model):
image = cv2.imread('Temp.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_image = imresize(gray_image, [100, 120])
gray_image = gray_image.reshape(1, 100, 120, 1)
prediction = model.predict_on_batch(gray_image)
predicted_class = np.argmax(prediction)

From scipy github issue (it has been removed since 1.3.0)
Functions from scipy.interpolate (spleval, spline, splmake,
and spltopp) and functions from scipy.misc (bytescale,
fromimage, imfilter, imread, imresize, imrotate,
imsave, imshow, toimage) have been removed. The former set has
been deprecated since v0.19.0 and the latter has been deprecated since v1.0.0.
Similarly, aliases from scipy.misc (comb, factorial,
factorial2, factorialk, logsumexp, pade, info, source,
who) which have been deprecated since v1.0.0 are removed.
SciPy documentation for v1.1.0 <https://docs.scipy.org/doc/scipy-1.1.0/reference/misc.html>__
can be used to track the new import locations for the relocated functions.
You can either downgrade scipy or follow the steps here
in vis/visualization/saliency.py
replace: from scipy.misc import imresize
to: import cv2
then
replace: heatmap = imresize(heatmap, input_dims, interp='bicubic', mode='F')
to:
heatmap = cv2.resize(src=heatmap,
dsize=input_dims,
interpolation=cv2.INTER_CUBIC)

Related

Module 'dateutil' has no attribute 'parser' - Dateutil - Python

I am trying to download a pre-trained tensorflow model. I am using the below code
import numpy as np
import time
import PIL.Image
import IPython.display as display
import matplotlib.pylab as plt
import tensorflow as tf
import tensorflow_hub as hub
import datetime
from tensorflow.keras.preprocessing import image
from dateutil import parser
from keras.applications.inception_v3 import InceptionV3
model = InceptionV3()
model.summary()
I am getting the following error
AttributeError: module 'dateutil' has no attribute 'parser'
I am using python -3.7 and TF-2.7, python-dateutil-2.8.1
Please help me fix this. Thank You :)
The correct import syntax is:
import dateutil.parser
and then:
parser.parse(time_string)
or:
from dateutil.parser import parse
parse(time_string)
Documentation: https://dateutil.readthedocs.io/en/stable/parser.html

Why are the libraries in Utils.py not loading?

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?

how to solve the problem of img_to_array throwing an array error? [duplicate]

How to troubleshoot this? I've tried setting dtype=None in the image.img_to_array method.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
from keras.preprocessing import image
image_size = (180, 180)
batch_size = 32
model = keras.models.load_model('best_model.h5')
img = keras.preprocessing.image.load_img(
"GarnetCreek_7-15-2019.jpeg", target_size=image_size
)
img_array = image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create batch axis
predictions = model.predict(img_array)
score = predictions[0]
This raises the following error:
Traceback (most recent call last):
img_array = image.img_to_array(img, dtype=None)
return image.img_to_array(img, data_format=data_format, **kwargs)
x = np.asarray(img, dtype=dtype)
return array(a, dtype, copy=False, order=order)
TypeError: __array__() takes 1 positional argument but 2 were given
Has anyone seen this before? Many thanks!
This error sometimes is due to a bug in Pillow 8.3.0 as it is here. (You may not use import PIL directly in your code, however some libraries such as tf.keras.preprocessing.image.load_img use PIL internally)
So, downgrading from PIL 8.3.0 to 8.2.0 may work.
Check PIL version:
import PIL
print(PIL.__version__)
If it is 8.3.0, then you may downgrade to 8.2.0:
!pip install pillow==8.2.0

cannot import name 'imagenet_utils' from 'tensorflow.keras.applications'

i have the following python imports with in Jupyter Notebook.
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import Model
from tensorflow.keras.applications import imagenet_utils
from sklearn.metrics import confusion_matrix
import itertools
import os
import shutil
import random
import matplotlib.pyplot as plt
%matplotlib inline
But i keep getting the following error
ImportError: cannot import name 'imagenet_utils' from 'tensorflow.keras.applications' (C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\api_v2\keras\applications_init_.py)
when i search for **cannot import name 'imagenet_utils' from 'tensorflow.keras.applications' **in google i dont get much helpful information.
Has anyone come across this at all?
change
from tensorflow.keras.applications import imagenet_utils
to
from keras.applications import imagenet_utils
i managed to solve my issue.
first i ran the following to update all modules.
conda update --all
Then i used 'from keras.applications import imagenet_utils'
instead of '#from tensorflow.keras import imagenet_utils'

how to call a module in a function in pp where that fuction has other functions in it?

I'm currently using parallel python ,and in the parameters of job_server.submit i added the library in modules but the problem is that even that library has other librairies in it .so what should i do ?
Here is the code i'm trying to run:
from tools.demo import detect_cn
import pp
job_server = pp.Server()
f1 = job_server.submit(detect_cn, (filename,),modules=('tools.demo',))
f2 = job_server.submit(detect_cn, (filename1,),modules=('tools.demo',))
cnis, preproc_time, roi_file_images=f1()
cnis1, preproc_time1, roi_file_images1=f2()
and this is part of code of demo.py
import _init_paths
from fast_rcnn.config import cfg
from fast_rcnn.test import im_detect
from fast_rcnn.nms_wrapper import nms
from utils.timer import Timer
from ocr.clstm import clstm_ocr
from ocr.clstm import clstm_ocr_calib
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import caffe, os, sys, cv2
import argparse
import werkzeug
import datetime
import math
import pytesseract
from PIL import Image
def detect_cn(filename):
cfg.TEST.HAS_RPN = True # Use RPN for proposals
args = parse_args()
prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0],
'faster_rcnn_alt_opt', 'faster_rcnn_test.pt')
caffemodel = os.path.join(cfg.DATA_DIR, 'faster_rcnn_models',
NETS[args.demo_net][1])
if not os.path.isfile(caffemodel):
raise IOError(('{:s} not found.\nDid you run ./data/script/'
'fetch_faster_rcnn_models.sh?').format(caffemodel))
if args.cpu_mode:
caffe.set_mode_cpu()
else:
caffe.set_mode_gpu()
caffe.set_device(args.gpu_id)
cfg.GPU_ID = args.gpu_id
net = caffe.Net(prototxt, caffemodel, caffe.TEST)
print '\n\nLoaded network {:s}'.format(caffemodel)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Demo for CN image...'
return demo2(net, filename)
Do you think i should load all those librairies in modules of job server.submit?
I want to use the pp bacause detect_cn takes 2 minutes to give results
any ideas?
Yes, you should import all these modules when wou submit your function into the execution queue.
f1 = job_server.submit(detect_cn, (filename,),modules=("math","numpy", ...))

Categories