Requests not defined after importing from a file - python

I have imported a file image_function.py to my notebook. However when i tried using one of the functions im_reverse, it gave me an error.
Code:
import image_function
image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
Error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-61-afc744ac8a12> in <module>()
1 import image_function
----> 2 image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
/content/image_function.py in im_reverse(image_path, reverse, url)
45 mat_image_column_reverse[c][i] = mat_image_reverse[j][i]
46 c += 1
---> 47
48 plt.axis('off')
49
NameError: name 'requests' is not defined
The error happened before it reached the code for reversing vertically, which is down below.
What's inside image_function:
#libraries:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import imshow
from PIL import Image
import copy
import requests
from io import BytesIO
This is the code after the error:
def im_reverse(image_path, reverse = 'horizontal', url = True):
if url == True:
response = requests.get(image_path)
with Image.open(BytesIO(response.content)) as image:
mat_image = np.array(image, dtype=int)
m, n, depth = mat_image.shape
if reverse == 'horizontal':
mat_image_reverse = copy.deepcopy(mat_image)
mat_image_rows_reverse = copy.deepcopy(mat_image)
for i in range(m):
c = 0
for j in range(n-1,-1,-1):
mat_image_rows_reverse[i][c] = mat_image_reverse[i][j]
c += 1
plt.axis('off')
return imshow(mat_image_rows_reverse)
I have tried a lot of solutions on the web. However i dont see anything wrong. I have also tried a deliberate from requests import get or !pip install requests and it still didn't work.
Can anyone please offer a solution. Thanks

It sounds like you need to install requests:
python3 -m pip install requests

Related

Importing a .tif into Jupyter Notebook using python script

I have been trying to import a .tif into python using the following code:
image = 'location/map_Western_Cape.tif' #use same location as above
geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
image_Gauteng = 'location/map_Gauteng.tif' #use same location as above
geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
However, I keep getting this error message:
AttributeError Traceback (most recent call last)
Input In [11], in <cell line: 4>()
1 # Load the .tif from local machine
3 image = 'C:/Users/kiral/OneDrive - Stellenbosch University/BScHons Global Change/Guy/map_Western_Cape.tif' #use same location as above
----> 4 geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
6 image_Gauteng = 'C:/Users/kiral/OneDrive - Stellenbosch University/BScHons Global Change/Guy/map_Gauteng.tif' #use same location as above
7 geemap.plot_raster(image, cmap='terrain', figsize=(15, 10))
File ~\anaconda3\lib\site-packages\geemap\common.py:12559, in plot_raster(image, band, cmap, proj, figsize, open_kwargs, **kwargs)
12557 try:
12558 import pvxarray
> 12559 import rioxarray
12560 import xarray
12561 except ImportError:
File ~\anaconda3\lib\site-packages\rioxarray\__init__.py:6, in <module>
3 __author__ = """rioxarray Contributors"""
4 __email__ = "alansnow21#gmail.com"
----> 6 import rioxarray.raster_array # noqa
7 import rioxarray.raster_dataset # noqa
8 from rioxarray._io import open_rasterio # noqa
File ~\anaconda3\lib\site-packages\rioxarray\raster_array.py:28, in <module>
14 from typing import (
15 Any,
16 Dict,
(...)
24 Union,
25 )
27 import numpy as np
---> 28 import rasterio
29 import rasterio.mask
30 import rasterio.warp
File ~\anaconda3\lib\site-packages\rasterio\__init__.py:44, in <module>
41 import warnings
43 import rasterio._loading
---> 44 with rasterio._loading.add_gdal_dll_directories():
45 from rasterio._show_versions import show_versions
46 from rasterio._version import gdal_version, get_geos_version, get_proj_version
AttributeError: partially initialized module 'rasterio' has no attribute '_loading' (most likely due to a circular import)
I have tried installing all of the listed modules, but that ended up getting a bunch of errors too.
Could anyone recommend a way to import these tifs?

AttributeError: 'IcclimLogger' object has no attribute 'timezone' jupyter notebook

I have following block of code:
i want to use ICCLIM (Indice Calculation CLIMate) is a Python library
To calculate some indices
how to solve this problem ??
files = ['tasmax_day_CNRM-CM5_historical_r1i1p1_19950101-19991231.nc', 'tasmax_day_CNRM-CM5_historical_r1i1p1_20000101-20041231.nc', 'tasmax_day_CNRM-CM5_historical_r1i1p1_20050101-20051231.nc']
dt1 = datetime.datetime(1998,1,1)
dt2 = datetime.datetime(2005,12,31)
out_f ='SU_JJA_CNRM-CM5_historical_r1i1p1_1998-2005.nc' # OUTPUT FILE: summer season values of SU
icclim.index(index_name='SU', in_files=files, var_name='tasmax', time_range=[dt1, dt2], slice_mode='JJA', out_file=out_f)
dt1 = datetime.datetime(1998,1,1)
dt2 = datetime.datetime(2005,12,31)
out_f = 'SU_JJA_CNRM-CM5_historical_r1i1p1_1998-2005.nc' # OUTPUT FILE: summer season values of SU
icclim.index(index_name='SU', in_files=files, var_name='tasmax', time_range=[dt1, dt2], slice_mode='JJA', out_file=out_f)
and the import list is
import numpy
import cython
import netcdftime
import cftime
import netCDF4
import sys
import glob
import os
import datetime
import dask
from netCDF4 import Dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import xarray
import nc_time_axis
import logging
import pytest
import setuptools
import xclim
import icclim
we i run the code the error keep show
here is the error
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2572/579676545.py in <module>
2 dt2 = datetime.datetime(1986,12,31)
3
----> 4 icclim.index(index_name='CD', in_files='C:/Users/Dana/Desktop/icclim/pr_year_1986.nc',time_range=[dt1, dt2], var_name='pr', slice_mode='year', out_file='C:/Users/Dana/Desktop/icclim/new_pr_year_1986.nc')
C:\ProgramData\Anaconda\lib\site-packages\icclim\main.py in index(in_files, var_name, index_name, slice_mode, time_range, out_file, threshold, transfer_limit_Mbytes, callback, callback_percentage_start_value, callback_percentage_total, base_period_time_range, window_width, only_leap_years, ignore_Feb29th, interpolation, out_unit, netcdf_version, user_index, save_percentile, logs_verbosity, indice_name, user_indice)
127 log.set_verbosity(logs_verbosity)
128
--> 129 log.start_message()
130 callback(callback_percentage_start_value)
131 if indice_name is not None:
C:\ProgramData\Anaconda\lib\site-packages\icclim\icclim_logger.py in start_message(self)
62
63 # flake8: noqa
---> 64 time_now = time.asctime(time.gmtime()) + " " + self.timezone
65 if self.verbosity == Verbosity.SILENT:
66 return
AttributeError: 'IcclimLogger' object has no attribute 'timezone'
Sorry for the late reply. This was due to a bug within icclim and it has been fixed in a later version.
I advise you to try the latest version (5.1.0) available on pypi or conda-forge.

How do I fix "No module named 'easysnmp'"

when I try to run the code. I am getting an error.
The error is
Traceback (most recent call last):
File "A2.py", line 2, in <module>
from easysnmp import Session
ImportError: No module named 'easysnmp'
Note: I am getting the above error.Even though, I have installed easysnmp module.
The code is
#!/usr/bin/python
from easysnmp import Session
import argparse
import time
parser = argparse.ArgumentParser(description='probe')
parser.add_argument('cred',help='credentials')
parser.add_argument('freq',type=float,help='enter frequency')
parser.add_argument('samples',type=int,help='enter samples')
parser.add_argument('oid',nargs='+',help='enter oid')
args=parser.parse_args()
t=1/args.freq
s=args.samples
cred1=args.cred
ip,port,comm=cred1.split(":")
count=0
session=Session(hostname=ip,remote_port=port,community=comm, version=2,timeout=2,retries=1)
args.oid.insert(0, '1.3.6.1.2.1.1.3.0')
old=[]
out1=[]
t4=0
while (count!=s):
t1=time.time()
new = session.get(args.oid)
t2=time.time()
if len(new)==len(old):
newtime=float(new[0].value)/100
oldtime=float(old[0].value)/100
if args.freq > 1:
tdiff = newtime-oldtime
if args.freq <= 1:
tdiff1 = t1-t4
if tdiff!=0:
tdiff = int(tdiff1)
else:
tdiff = int(t)
for i in range(1,len(args.oid)):
if new[i].value!="NOSUCHINSTANCE" and old[i].value!="NOSUCHINSTANCE":
a=int(new[i].value)
b=int(old[i].value)
if a>=b:
out=(a-b)/tdiff
out1.append(out)
if a<b and new[i].snmp_type=="COUNTER64":
out=((2**64+a)-b)/tdiff
out1.append(out)
if a<b and new[i].snmp_type=="COUNTER32":
out=((2**32+a)-b)/tdiff
out1.append(out)
else:
print t1, "|"
count=count+1
if len(out1)!=0:
sar = [str(get) for get in out1]
print int(t1) ,'|', ("|" . join(sar))
old = new[:]
t4=t1
del out1[:]
t3=time.time()
if t-t3+t1>0:
time.sleep(t-t3+t1)
else:
time.sleep(0.0)
Try to put import easysnmp at the top of your code, it solved the problem for me at a similar situation!
My wild guess is that you installed the module for python 3 and used python 2 or the other way around.
Try
pip install easysnmp
or
pip3 install easysnmp

Python Error in Displaying Image

On this Image
I am trying to apply:
from PIL import Image
img0 = PIL.Image.open('Entertainment.jpg')
img0 = np.float32(img0)
showarray(img0/255.0)
And I get this error:
TypeErrorTraceback (most recent call last)
<ipython-input-20-c181acf634a8> in <module>()
2 img0 = PIL.Image.open('Entertainment.jpg')
3 img0 = np.float32(img0)
----> 4 showarray(img0/255.0)
<ipython-input-8-b253b18ff9a7> in showarray(a, fmt)
11 f = BytesIO()
12 PIL.Image.fromarray(a).save(f, fmt)
---> 13 display(Image(data=f.getvalue()))
14
15 def visstd(a, s=0.1):
TypeError: 'module' object is not callable
I can't understand why.
What is not callable here?
How can I just display the image?
Image is a module that you imported
from PIL import Image
You can't call it
Image(data=f.getvalue())
There's a show method that may be useful
img0 = PIL.Image.open('Entertainment.jpg')
img0.show()
The problem may stem from how you've imported the display() function. If your import line is:
import IPython.display as display
then you need to invoke display.display() to show the image. For example:
import IPython.display as display
my_image = Image.open('something.jpg')
display.display(my_image)
If you instead invoke the function as
import IPython.display as display
my_image = Image.open('something.jpg')
display(my_image) # INCORRECT
# TypeError: 'module' object is not callable
then you will indeed get the error message in your original post because display is referring to a module, not a function.
Alternatively, if you import the display() function in the following manner, your code will work:
from IPython.display import display
my_image = Image.open('something.jpg')
display(my_image)

Python: AttributeError

When I run my script I get this error:
File "test_cm.py", line 34, in
labels = labels_img.get_data() AttributeError: 'tuple' object has no attribute 'get_data'
from dipy.tracking.eudx import EuDX
from dipy.reconst import peaks, shm
from dipy.tracking import utils
from dipy.data import read_stanford_labels
from dipy.io.gradients import read_bvals_bvecs
import numpy as np
import matplotlib.pyplot as plt
import nibabel as nib
source="prova11/"
path=source
print('loading data')
bvals,bvecs=read_bvals_bvecs(source+"bvals",source+"bvecs")
bvals[bvals < 10] = 0
img = nib.load(source+"segment-TO-b0.nii")
data = img.get_data()
affine=img.affine
labels_img = read_stanford_labels()
labels = labels_img.get_data()
read_stanford_labels() returns a tuple, and tuples don't have a get_data() method which is why the error says AttributeError: 'tuple' object has no attribute 'get_data'.
You should go over your read_stanford_labels function and see why it returns a tuple, which isn't what you expected.
Edit: By going over the documentation/example your code should be
hardi_img, gtab, labels_img = read_stanford_labels() instead of
labels_img = read_stanford_labels().
Alternatively, if you don't need the first 2 values, you can use
labels_img = read_stanford_labels()[-1] or
*_, labels_img = read_stanford_labels().

Categories

Resources