ipython notebook read multiple images and display in CELL - ipython

How do I do the above ? This is my code but it doesn't work nothing is displayed
from PIL import Image
import glob
image_list = []
for filename in glob.glob('<my directory>.pgm'):
im=Image.open(filename)
image_list.append(im)
import matplotlib.pyplot as plt
for i in range(10):
plt.figure()
plt.imshow(image_list[i])
I would like it to be displayed in the cell

If you're interested in a much simpler and faster way of displaying images I recommend IPyPlot package:
import ipyplot
ipyplot.plot_images(images_list, max_images=20, img_width=150)
It's capable of displaying hundreds of images in a grid-like format within just 60-70ms
You would get a plot similar to this:

In your case, you should add %matplotlib inlinebefore your code and make sure that after plt.imshow(images_list) you add plt.show() as well so matplotlib renders your images.

Related

How to convert a .tif PIL image to a torch tensor?

I have some .tif images and I'm reading them in as PIL image.
I know there is a ToPILimage transform
but I could not find a from_PILimage() akin to from_numpy()
as of right now I have this ugly looking thing:
img = torch.from_numpy(np.array(Image.open('path/image.tif')))
Could you show me a better way?
Thanks in advance!
Similar to torchvision.transforms.ToPILImage(), you can use torchvision.transforms.ToTensor() directly. Example from PyTorch docs
There's also the functional equivalent torchvision.functional.to_tensor().
img = Image.open('someimg.png')
import torchvision.transforms.functional as TF
TF.to_tensor(img)
from torchvision import transforms
transforms.ToTensor()(img)

Add text for different part of line chart plot in plotly python

I draw a figure using plotly (python) as shown in below.
Now my aim is to show all points in same color but add different text for each colored part from this figure. For example, for the blue part I want to add the text AAA and for the red part BBB. How to do that in plotly?
I have simulated data with features that will generate a graph similar to one you have shown
there are three ways to add labels
labels against traces in legend
as additional scatter plots with mode="text"
as annotations on the figure
All three of these are demonstrated below. It does assume you have a working knowledge of pandas
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
df = pd.DataFrame({"AAA":np.concatenate([np.random.uniform(1,5,20), np.full(20,np.nan)]),
"BBB":np.concatenate([np.full(20,np.nan), np.random.uniform(1,5,20), ])})
# create two traces, where traces are in legend to label AAA & BBB
fig = px.scatter(df, x=df.index, y=["AAA","BBB"]).update_traces(mode="lines+markers")
# additionally create text trace, that are last AAA & BBB
lastAAA = df.loc[~df["AAA"].isna()].iloc[-1]
lastBBB = df.loc[~df["BBB"].isna()].iloc[-1]
fig.add_trace(go.Scatter(x=[lastAAA.name], y=[lastAAA["AAA"]], text="AAA", mode="text", showlegend=False))
fig.add_trace(go.Scatter(x=[lastBBB.name], y=[lastBBB["BBB"]], text="BBB", mode="text", showlegend=False))
# additionally add annotations
fig.add_annotation(x=lastAAA.name, y=lastAAA["AAA"], text="AAA")
fig.add_annotation(x=lastBBB.name, y=lastBBB["BBB"], text="BBB")

Nib.load() error - Trying to load PNG and DICOM images to be resized for FCNN

Have 40 DICOM and 40 PNG images (data and their masks) for a Fully CNN that are loaded into my Google Drive and have been found by the notebook via the print(os.listdir(...)), as evidenced below in the first block of code where all the names of the 80 data in the above sets are listed.
Also have globbed all of the DICOM and PNG into img_path and mask_path, both with lengths of 40, in the second block of code that is below.
Now attempting to resize all of the images to 256 x 256 before inputting them into the U-net like architecture for segmentation. However, cannot load them via the nib.load() call, as it cannot work out the file type of the DCM and PNG files, even though for the latter it will not error but still produce an empty set of data like the last block of code yields.
Assuming that, once the first couple of lines inside the for loop in the third block of code are rectified, pre-processing should be completed and I can move onto the U-net implementation.
Have the current pydicom running in the Colab notebook and tried it in lieu of the nib.load() call, which produced the same error as the current one.
#import data as data
import pydicom
from PIL import Image
import numpy as np
import glob
import imageio
print(os.listdir("/content/drive/My Drive/Images"))
print(os.listdir("/content/drive/My Drive/Masks"))
pixel_data = []
images = glob.glob("/content/drive/My Drive/Images/IMG*.dcm");
for image in images:
dataset = pydicom.dcmread(image)
pixel_data.append(dataset.pixel_array)
#print(len(images))
#print(pixel_data)
pixel_data1 = [] ----------------> this section is the trouble area <-------
masks = glob.glob("content/drive/My Drive/Masks/IMG*.png");
for mask in masks:
dataset1 = imageio.imread(mask)
pixel_data1.append(dataset1.pixel_array)
print(len(masks))
print(pixel_data1)
['IMG-0004-00040.dcm', 'IMG-0002-00018.dcm', 'IMG-0046-00034.dcm', 'IMG-0043-00014.dcm', 'IMG-0064-00016.dcm',....]
['IMG-0004-00040.png', 'IMG-0002-00018.png', 'IMG-0046-00034.png', 'IMG-0043-00014.png', 'IMG-0064-00016.png',....]
0 ----------------> outputs of trouble area <--------------
[]
import glob
img_path = glob.glob("/content/drive/My Drive/Images/IMG*.dcm")
mask_path = glob.glob("/content/drive/My Drive/Masks/IMG*.png")
print(len(img_path))
print(len(mask_path))
40
40
images=[]
a=[]
for a in pixel_data:
a=resize(a,(a.shape[0],256,256))
a=a[:,:,:]
for j in range(a.shape[0]):
images.append((a[j,:,:]))
No output, this section works fine.
images=np.asarray(images)
print(len(images))
10880
masks=[] -------------------> the other trouble area <-------
b=[]
for b in masks:
b=resize(b,(b.shape[0],256,256))
b=b[:,:,:]
for j in range(b.shape[0]):
masks.append((b[j,:,:]))
No output, trying to solve the problem of how to fix this section.
masks=np.asarray(masks) ------------> fix the above section and this
print(len(masks)) should have no issues
[]
You are trying to load the DICOM files again using nib.load, which does not work, as you already found out:
for name in img_path:
a=nib.load(name) # does not work with DICOM files
a=a.get_data()
a=resize(a,(a.shape[0],256,256))
You already have the data from the DICOM files in the pixel_data list, so you should use these:
for a in pixel_data:
a=resize(a,(a.shape[0],256,256)) # or something similar, depending on the shape of pixel_data
...
Your last loop for mask in masks: is never executed because two lines about it you set masks = [].
It looks like it should to be for mask in mask_path:. mask_path is the list of mask file names.

How can I get a graph of graphs to display in Sage?

I am working in SageMathCloud and have the following code:
import networkx
import matplotlib.pyplot as plt
test5 = networkx.Graph()
example = graphs.BuckyBall
test5.add_node(example)
networkx.draw(test5)
plt.show()
and from what I read, should display a graph with a single vertex that has a graph inside of it, like this picture from this article. However, all it shows is a single vertex with nothing inside of it as shown: Is there any way to display the graph to look like the 1st picture, where the graphs (as vertices) are shown?

Preserving Axis annotation while interactively zooming in on a matplotlib basemap plot?

I'm creating a figure displaying the worldmap with some data on it (which is irrelevant here). Now I want to be able to zoom in on it using the Pan/Zoom-button or the Zoom-to-rectangle-button and then save the figure to a picture file once I'm done zooming in. The problem is that the axis annotations (and the lng-/lat-lines) are "hard-embedded" in the picture, which make them vanish when you zoom in.
Does anybody know how to get axis annotations that adapt to the zooming?
Here is a minimal working example (without any data):
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
fig = plt.figure(1, figsize=(12, 7))
m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\
llcrnrlon=-180,urcrnrlon=180,resolution='l') #,lat_ts=20
m.drawcoastlines(); m.fillcontinents(); m.drawcountries()
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,91.,30.),labels=[True, False, False, False], color='White')
m.drawmeridians(np.arange(-180.,181.,60.), labels=[False, False, False, True], color='White')
plt.show()
Just in case someone ever stumbles upon my question, here is what I came up with as a rather quick work-around. :-)
My intended application was to zoom in and then save the figure. Now I do not do that interactively but by entering the "zoomed bounding box" in the code and dynamically creating lng/lat-ticks with the following function (which needs an import numpy as np beforehand):
def calculateBasemapTicks(minMaxList, nrOfParalles = 3, nrOfMeridians = 3):
"""
Attempts to calculate meaningful ranges for .basemap.drawparallels
and .drawmeridians. Enter a <minMaxList> in the form
[lng_min, lng_max, lat_min, lat_max].
Note that you might get rather ugly floats. I suggest using formatting
as in ".drawparallels(..., fmt='%.4f')" or similar.
"""
pAdjust = (minMaxList[3]-minMaxList[2])*0.1
mAdjust = (minMaxList[1]-minMaxList[0])*0.1
parallels = np.linspace(minMaxList[2]+pAdjust,minMaxList[3]-pAdjust,
nrOfParalles)
meridians = np.linspace(minMaxList[0]+mAdjust,minMaxList[1]-mAdjust,
nrOfMeridians)
return parallels, meridians