I have a piece of python code that is intended to extract letters and label each region that contains an image.
I'm using google colab
I get the following error:
NameError Traceback (most recent call last)
in ()
1
----> 2 image = imageio.imread('https://pbs.twimg.com/profile_images/985792111713947648/7YD1ZYpe_400x400.jpg')
3
4
5
NameError: name 'imageio' is not defined```
Heres the full code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from scipy.misc import imageio.imread,imresize
from skimage.segmentation import clear_border
from skimage.morphology import label
from skimage.measure import regionprops
image = imageio.imread('https://pbs.twimg.com/profile_images/985792111713947648/7YD1ZYpe_400x400.jpg')
#apply threshold in order to make the image binary
bw = image < 120
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared,neighbors=8)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
print(label_image.max())
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(bw, cmap='jet')
You're using a function from a package you haven't imported yet. First you need to install imageio in your system (pip install imageio) and then include it in the code (and removing the other imread). The new code will be:
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from skimage.segmentation import clear_border
from skimage.morphology import label
If you're going to use imresize you will need to install pillow.
Related
import os
import imageio.v2 as imageio
import matplotlib.pyplot as plt #for displaying figure/image data
import pandas as pd
import plotly
import plotly.express as px
import plotly.graph_objects as go #for intearctive plots
import scipy.stats as ss # for statistical testing
import scikit_posthocs as so # for posthoc testing
from skimage import measure, morphology
from skimage.color import rgb2gray
from skimage.filters import (gaussian, threshold_yen)
from skimage.measure import regionprops_table
path = r'/Users/marzo/Downloads'
os.chdir(path)
imagename = 'Fish 2'
image = imageio.imread(imagename+'.jpg')
img = rgb2gray(image)
img= gaussian(img, sigma=1)
plt.imshow(img, cmap='gray')
block_size = 51
threshold = threshold_yen(img, block_size)
mask = img < threshold * 0.59
mask = morphology.remove_small_objects(mask, 400)
mask = morphology.remove_small_holes(mask, 5000)
plt.imshow(mask, cmap='gray')
I am trying to open an image using plt.imshow, but nothing is happening and I am not getting any errors though, can someone explain why is it not showing any images
I am trying to plot an image using SentinelHub-py. This is part of my the code:
from sentinelhub import SHConfig
config = SHConfig()
config.sh_client_id = "76186bb6-a02e-4457-9a9d-126e4fffaed4"
config.sh_client_secret = "aTlX[s:39vzA8p}HA{k*Zp!fJNF~(c7e.u7r21V!"
config.save()
%reload_ext autoreload
%autoreload 2
%matplotlib inline
#Import them
import os
import datetime
import numpy as np
import matplotlib.pyplot as plt
from sentinelhub import SHConfig
from sentinelhub import MimeType, CRS, BBox, SentinelHubRequest, SentinelHubDownloadClient, DataCollection, bbox_to_dimensions, DownloadRequest
from utils import plot_image
betsiboka_coords_wgs84 = [46.16, -16.15, 46.51, -15.58]
resolution = 60
betsiboka_bbox = BBox(bbox=betsiboka_coords_wgs84, crs=CRS.WGS84)
betsiboka_size = bbox_to_dimensions(betsiboka_bbox, resolution=resolution)
print(f'Image shape at {resolution} m resolution: {betsiboka_size} pixels')
"""
Utilities used by example notebooks
"""
import matplotlib.pyplot as plt
import numpy as np
def plot_image(image, factor=3.5/255, clip_range=(0,1)):
"""
Utility function for plotting RGB images.
"""
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 15))
if clip_range is not None:
ax.imshow(np.clip(image * factor, *clip_range), **kwargs)
else:
ax.imshow(image * factor, **kwargs)
ax.set_xticks([])
ax.set_yticks([])
which give me the following error:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6632/1226496077.py in <module>
9 from sentinelhub import MimeType, CRS, BBox, SentinelHubRequest, SentinelHubDownloadClient, DataCollection, bbox_to_dimensions, DownloadRequest
10
---> 11 from utils import plot_image
12
13 CLIENT_ID='76186bb6-a02e-4457-9a9d-126e4fffaed4'
ImportError: cannot import name 'plot_image' from 'utils' (c:\xxxxxxxxxxxx.py)
someone made a comment on this issue by saying:
"It seems that the utils package that you are calling is not the correct one. Try loading the utils.py from the examples folder, or that you can find [here][1] (i.e. copy the file to your working directory with your notebook)."
[1]: https://github.com/sentinel-hub/sentinelhub-py
I change my code to this:
"""
Utilities used by example notebooks
"""
import matplotlib.pyplot as plt
import numpy as np
def plot_image(image, factor=3.5/255, clip_range=(0,1)):
"""
Utility function for plotting RGB images.
"""
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 15))
if clip_range is not None:
ax.imshow(np.clip(image * factor, *clip_range), **kwargs)
else:
ax.imshow(image * factor, **kwargs)
ax.set_xticks([])
ax.set_yticks([])
still didn't plot the image.
Please, any suggestions?
You have to navigate to your utils.py. In my computer is:
(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/utils).
Later, you have to copy and paste the next script from:
https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/utils.py
Finally, you will be able to type in your python script: "from utils import plot_image"
Best,
Jose
I've been trying to iterate over files in a folder and show them for two seconds each using this code:
import time
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import imread
import glob
import cv2
im = []
for filepath in glob.iglob(r'C:\Users\dan20\Pictures\wedding\beeri and adn. photo/*.jpg'):
a = imread(filepath)
b = cv2.resize(a, dsize = (456,304))
im += [b]
fig,ax = plt.subplots()
for i in im:
time.sleep(2)
ax.axis('off')
ax.imshow(i)
plt.show()
For some reason I can't see the images as long as i use time.sleep().
How can I make each picture to appear for N amount of times?
How about using plt.pause :
import numpy as np
from matplotlib import pyplot as plt
im = [np.random.random((9,9)) for i in range(1,6)]
fig,ax = plt.subplots()
for i in im:
ax.cla()
ax.imshow(i)
ax.axis('off')
plt.pause(2)
which gives :
Here is the code i tried, please give me solution.
import numpy as np
import pylab
import mahotas as mh
from matplotlib import pyplot as plt
import cv2
dna = mh.imread('C:\Users\user!\Desktop\images\logo.png')
pylab.imshow(dna)
rows,cols = dna.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)
dst = cv2.warpAffine(dna,M,(cols,rows))
Error:
ValueError: too many values to unpack
I want to use the colormap "viridis" (http://bids.github.io/colormap/), and I won't be updating to the development version 1.5 quite yet. Thus, I have downloaded colormaps.py from https://github.com/BIDS/colormap. Unfortunately, I'm not able to make it work. This is what I do:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import colormaps as cmaps
img=mpimg.imread('stinkbug.png')
lum_img = np.flipud(img[:,:,0])
plt.set_cmap(cmaps.viridis)
imgplot = plt.pcolormesh(lum_img)
This gives me a ValueError, the traceback ending with,
ValueError: Colormap viridis is not recognized. Possible values are: Spectral, summer, coolwarm, ...
(And then the complete list of originally installed colormaps.)
Any thoughts on how to fix this issue?
To set viridis as your colormap using set_cmap, you must register it first:
import colormaps as cmaps
plt.register_cmap(name='viridis', cmap=cmaps.viridis)
plt.set_cmap(cmaps.viridis)
img=mpimg.imread('stinkbug.png')
lum_img = np.flipud(img[:,:,0])
imgplot = plt.pcolormesh(lum_img)
Rather than using set_cmap, which requires a matplotlib.colors.Colormap instance, you can set the cmap directly in the pcolormesh call
(cmaps.viridis is a matplotlib.colors.ListedColormap)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import colormaps as cmaps
img=mpimg.imread('stinkbug.png')
lum_img = np.flipud(img[:,:,0])
imgplot = plt.pcolormesh(lum_img, cmap=cmaps.viridis)
What I did is to just copy the
_viridis_data = [[0.267004, 0.004874, 0.329415],
[0.268510, 0.009605, 0.335427],
[0.269944, 0.014625, 0.341379],
:
[0.983868, 0.904867, 0.136897],
[0.993248, 0.906157, 0.143936]]
from https://github.com/BIDS/colormap/blob/master/colormaps.py
and add:
from matplotlib.colors import ListedColormap
viridis = ListedColormap(_viridis_data, name='viridis')
plt.register_cmap(name='viridis', cmap=viridis)
plt.set_cmap(viridis)
Download the colormaps.py from here,then:
import os,sys
scriptpath = "/Your downloading path/colormap-master/"
sys.path.append(os.path.abspath(scriptpath))
import colormaps as cmaps
Done!