python just import fails but works with from - python

Why does this not work:
import matplotlib.pyplot as plt
import os
import skimage
camera = skimage.io.imread(os.path.join(skimage.data_dir, 'camera.png'))
#plt.show(io.imshow(camera))
But using from skimage import io does. So this works:
import matplotlib.pyplot as plt
import os
import skimage # I still need to import skimage to get the data_dir
from skimage import io
camera = io.imread(os.path.join(skimage.data_dir, 'camera.png'))
#plt.show(io.imshow(camera))
I thought
import skimage
skimage.io."something"
Was equivalent to
from skimage import io
io."something"

I thought
import skimage
skimage.io."something"
Was equivalent to
from skimage import io
io."something"
It's not.
import skimage
causes python to look for the skimage module. Maybe there's a __init__.py that sets up what becomes visible and what is done when you import that module.

Related

ModuleNotFoundError: No module named 'u8darts'

I am trying to use darts library to forecast price using transformer neural nets. through ubuntu20.4 terminal and python 3.10.
The below is my code, where I just calling and Importing necessary libraries:
from os.path import dirname, basename
from os import getcwd
import sys
def fix_pythonpath_if_working_locally():
"""Add the parent path to pythonpath if current working dir is darts/examples"""
cwd = getcwd()
if basename(cwd) == 'examples':
sys.path.insert(0, dirname(cwd))
fix_pythonpath_if_working_locally()
# Commented out IPython magic to ensure Python compatibility.
# %load_ext autoreload
# %autoreload 2
# %matplotlib inl
import pandas as pd
import numpy as np
import datetime
import time
from datetime import datetime
from sklearn import preprocessing
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import shutil
import os
import seaborn as sns
import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm_notebook as tqdm
import u8darts
from u8darts import TimeSeries
from u8darts.dataprocessing.transformers import Scaler
from u8darts.models import TransformerModel, ExponentialSmoothing
from u8darts.metrics import mape
from u8darts.utils.statistics import check_seasonality, plot_acf
import warnings
warnings.filterwarnings("ignore")
import logging
But I have got this error:
Traceback (most recent call last):
File "/vol/0/home/kherad/reihane/darts.py", line 59, in <module>
import u8darts
ModuleNotFoundError: No module named 'u8darts'
How can I fix this error?(I have use pip install u8darts in terminal and installed successfully)

How do you load an image on VSC for Python

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('25.png')
plt.imshow(image)
I've used this code here to try and produce the image but it keeps saying that the module does not exist.
First, you should import 'matplotlib.pyplot'
Second, make sure the photo is in the same directory as your code is.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('25.png')
imgplot = plt.imshow(image)

Error opening '*.wav': File contains data in an unknown format

I'm trying to run the following code:
import os
import librosa
import IPython.display as ipd
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
import warnings
warnings.filterwarnings("ignore")
train_audio_path = 'train/audio/'
samples, sample_rate = librosa.load(train_audio_path+'yes/0a7c2a8d_nohash_0.wav', sr = 16000)
But get two errors:
Error opening 'train/audio/yes/0a7c2a8d_nohash_0.wav': File contains data in an unknown format
and
NoBackendError:
I've tried downloading ffmpeg and gstreamer to fix the second error but no luck. I'm not sure what to do about the first error as I have imported libraries that should be able to handle .wav files.
Thank you for your help in advance.

What is the json file I need to read?

enter image description hereI need to download satellite images using python. I have found a code in GitHub but I did not understand what at this line. Please help me what it exactly is.
Visit https://github.com/kscottz/PythonFromSpace/blob/master/TheBasics.ipynb
import sys
import os
import json
import scipy
import urllib
import datetime
import urllib3
import rasterio
import subprocess
import numpy as np
import pandas as pd
import seaborn as sns
from osgeo import gdal
from planet import api
from planet.api import filters
from traitlets import link
import rasterio.tools.mask as rio_mask
from shapely.geometry import mapping, shape
from IPython.display import display, Image, HTML
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
urllib3.disable_warnings()
from ipyleaflet import (
Map,
Marker,
TileLayer, ImageOverlay,
Polyline, Polygon, Rectangle, Circle, CircleMarker,
GeoJSON,
DrawControl
)
%matplotlib inline
# will pick up api_key via environment variable PL_API_KEY
# but can be specified using `api_key` named argument
api_keys = json.load(open("apikeys.json",'r'))
client = api.ClientV1(api_key=api_keys["PLANET_API_KEY"])
# Make a slippy map to get GeoJSON
api_keys = json.load(open("apikeys.json",'r'))
client = api.ClientV1(api_key=api_keys["PLANET_API_KEY"])
What is the meaning of these two lines. What file should I upload for apikeys.json
You should follow this link to get an API Key.
https://support.planet.com/hc/en-us/articles/212318178-What-is-my-API-key-
apikeys.json is a JSON file of following format/content in json:
{"PLANET_API_KEY":"<Some API Key here>"}
json.load(...) API loads this json file as a dictionary

Can not save file using the below python code. Error: numpy.ndarray object has no attribute 'save'

import os
import sys
import numpy as np
import scipy
import pylab
import pymorph
import mahotas
import matplotlib.pyplot as plt
import Image
from scipy import ndimage
from pymorph import regmax
from PIL import Image
path='all_images'
for file in os.listdir(path):
current = os.path.join(path, file)
extension = os.path.splitext(current)[-1]
fileType = extension.upper()
print(current)
if os.path.isfile(current):
img = mahotas.imread(current)
imgf = ndimage.gaussian_filter(img, 8)
pylab.gray()
imgf.save('dnaa.gif')
Can not save file using the below python code. Error: numpy.ndarray object has no attribute 'save'. Can anyone help how to save file using pylab. I guss the last line of the code has some issue.
Use mahotas.imsave('dnaa.gif', imgf) instead. The NumPy array you get from gaussian_filter doesn't have save functionality built in.

Categories