How can I extract the information from a tree using viewer? - python

from astropy.io import fits
import matplotlib.pyplot as plt
from astrodendro import Dendrogram, pp_catalog
import numpy as np
fname = "/home/citlali/Documentos/Servicio/m/m8093-1901/manga-8093-1901.Pipe3D.cube.fits.gz"
image = fits.open(fname)
DATOS = image["FLUX_ELINES"].data
img = DATOS[45, :, :]
d = Dendrogram.compute(img, min_value=0, min_delta=0, min_npix=0.1)
d.trunk[0]
v = d.viewer()
v.show()
This is my code and when I plotted I got this where I select whatever regions I want (for example, red and green). So, I'm looking for extract the information of those regions but I don't know how to do it. If anyone have an idea o know a function, I will appreciate it. Also it has to be atuomated.
Thank you.

Related

How to plot scatterplot using matplotlib from arrays (using strings)? Python

I have been trying to plot a 3D scatterplot from a pandas array (I have tried to convert the data over to numpy arrays and strings to put into the system). However, the error ValueError: s must be a scalar, or float array-like with the same size as x and y keeps popping up. My data for Patient ID is in the format of EMR-001, EMR-002 etc after blanking it out. My data for Discharge Date is converted to become a string of numbers like 20200120. My data for Diagnosis Code is a mix of characters like 001 or 10B.
I have also tried to look online at some of the other examples but have not been able to identify any areas. Could I seek your advice for anything I missed out or code I can input?
I'm using Python 3.9, UTF-8. Thank you in advanced!
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#importing csv data via pd
A = pd.read_csv('input.csv') #import file for current master list
Diagnosis_Des = A["Diagnosis Code"]
Discharge_Date = A["Discharge Date"]
Patient_ID = A["Patient ID"]
B = Diagnosis_Des.to_numpy()
#B1 = np.array2string(B)
#print(B.shape)
C = Discharge_Date.to_numpy() #need to change to data format
#C1 = np.array2string(C)
#print(C1)
D = Patient_ID.to_numpy()
#D1 = np.array2string(D)
#print(D.shape)
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
sequence_containing_x_vals = D
sequence_containing_y_vals = B
print(type(sequence_containing_y_vals))
sequence_containing_z_vals = C
print(type(sequence_containing_z_vals))
plt.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()

Python "make_transforms" shows list index error while aligning fits images

I am trying to align 4 fits (V2.fits,V3.fits,V4.fits and, V5.fits) with respect to a reference fits file (V1.fits). I tried the following by employing the python fits_align package :
from fits_align.ident import make_transforms
from fits_align.align import affineremap
from glob import glob
from astropy.io import fits
from numpy import shape
import os
img_list = sorted(glob(os.path.join("*.fits")))
ref_image = img_list[0]
images_to_align = img_list[1:]
print(img_list) # List of all images
print(ref_image) # Reference image
print(images_to_align) # Images to align
identifications = make_transforms(ref_image, images_to_align)
aligned_images = [ref_image]
for id in identifications:
if id.ok:
alignedimg = affineremap(id.ukn.filepath, id.trans, outdir=tmpdir)
aligned_images.append(alignedimg)
I get the following index error:
What could be the reasons for this error? please suggest possible solutions

How to display images with google facets dive?

I am getting started with google facets, but I am finding the documentation insufficient.
I want to use facets dive to visualize images like they do here for cifar-10 . There is another example here using the Quick, draw! dataset.
However, I cannot find how to set it up.
That is about what I have so far, the code works all right:
from sklearn.datasets import fetch_mldata
from sklearn.decomposition import PCA
import pandas as pd
import numpy as np
from IPython.core.display import display, HTML
#load data:
mnist = fetch_mldata("MNIST original")
idx =np.random.randint(70000, 1000) #get random 1000 samples
X = mnist.data[idx]/255.0
y = mnist.target[idx]
#dimensionality reduction to get 3 features
pca = PCA(n_components=3)
pca_result = pca.fit_transform(X)
#put everything in a dataframe
df = df_pca = pd.DataFrame(data = pca_result, columns = [["pca-one", "pca-two", "pca-three"]])
df['y'] = y
#display facets dive
jsonstr = df.to_json(orient='records')
HTML_TEMPLATE = """<link rel="import" href="https://raw.githubusercontent.com/PAIR-code/facets/master/facets-dist/facets-jupyter.html">
<facets-dive id="elem" height="600"></facets-dive>
<script>
var data = {jsonstr};
document.querySelector("#elem").data = data;
</script>"""
html = HTML_TEMPLATE.format(jsonstr=jsonstr)
display(HTML(html))
This script works fine, but I just get circles with the labels (or whichever feature I choose), but I don't see how to integrate the actual images in there. The only hint I have so far is that I need the facets_atlasmaker for that, but I found the documentation rather insufficient.
If something is not clear, please let me know in the comments, I can try do add more relevant information then.

Importing images for manifold Isomap

There are 192 x 144 pixel images. They should be imported to a Python list so that the items in the list are NDArray instances. New dataframe should be created from the list and that dataframe should be given to Isomap. iso.fit(df) fails with the errors
array = array.astype(np.float64)
ValueError: setting an array element with a sequence.
I have spent more than one day trying to figure out how the NDArrays should be processed and the dataframe loaded with them. No luck. Any help would be appreciated.
import pandas as pd
from scipy import misc
import glob
from sklearn import manifold
samples = []
for filename in glob.glob('Datasets/ALOI/32/*.png'):
img = misc.imread(filename, mode='I')
samples.append(img)
df = pd.DataFrame.from_records(samples, coerce_float=True)
iso = manifold.Isomap(n_neighbors=6, n_components=3)
iso.fit(df)
If those are gray scale images from the ALOI, you probably want to treat each pixel's brightness as a feature. Therefore, you should flatten the img array with img.reshape(-1). The revised code follows:
import pandas as pd
from scipy import misc
import glob
from sklearn import manifold
samples = []
for filename in glob.glob('Datasets/ALOI/32/*.png'):
img = misc.imread(filename, mode='I')
# the following line changed
samples.append(img.reshape(-1))
df = pd.DataFrame.from_records(samples, coerce_float=True)
iso = manifold.Isomap(n_neighbors=6, n_components=3)
iso.fit(df)

ndimage script mis-behaving

I have a script that reads in image data, and then iterates over the images with the median filter in scipy.ndimage. From the iteration i create new arrays.
However when i attempt to run the script with
run filtering.py
The filtering does not seem to work. The new arrays (month_f) are the same as the old ones.
import matplotlib.pyplot as plt
import numpy as numpy
from scipy import ndimage
import Image as Image
# Get images
#Load images
jan1999 = Image.open('jan1999.tif')
mar1999 = Image.open('mar1999.tif')
may1999 = Image.open('may1999.tif')
sep1999 = Image.open('sep1999.tif')
dec1999 = Image.open('dec1999.tif')
jan2000 = Image.open('jan2000.tif')
feb2000 = Image.open('feb2000.tif')
#Compute numpy arrays
jan1999 = numpy.array(jan1999)
mar1999 = numpy.array(mar1999)
may1999 = numpy.array(may1999)
sep1999 = numpy.array(sep1999)
dec1999 = numpy.array(dec1999)
jan2000 = numpy.array(jan2000)
feb2000 = numpy.array(feb2000)
########### Put arrays into a list
months = [jan1999, mar1999, may1999, sep1999, dec1999, jan2000, feb2000]
############ Filtering = 3,3
months_f = []
for image in months:
image = scipy.ndimage.median_filter(image, size=(5,5))
months_f.append(image)
Any help would be much appreciated :)
This is rather a comment but due to reputation limits I'm not able to write one.
The way you import your modules is a bit strange. Especially "import .. as" with the idential name. I think a more pythonian way would be
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
from PIL import Image
and then call
image = ndimage.median_filter(image, size=(...))
When I run your steps with a RGB test image it seems to work.
What does jan1999.shape return?

Categories

Resources