Radon transform apply scale change problem in python - python

import nibabel as nib
import numpy as np
import torch
from skimage.transform import radon,iradon
dir = "/hdd1/Data/3D_CT/train/000000098656.nii.gz"
nib_loader = nib.load(dir).get_fdata()
theta = np.linspace(0,180,360)
slices = nib_loader[150,:,:]
rt = radon(slices,theta,circle=True)
print(slices.max())
print(slices.min())
print(rt.max())
print(rt.min())**
slices.max()=1220.0
slices.min()=-1024.0
rt.max()=0.0
rt.min()=-510128.35438634525
radon transform change image scale how to fix the radon transform scale?
i want radon transform image sclae same slices image scale

Related

How to reduce contrast of a NumPy array?

I want to reduce the contrast of my whole dataset as an experiment. The dataset is in a NumPy array of np.array(X).reshape(-1, 28, 28, 1) I tried to use the library Albumentations, which works really well for motion blur and Gaussian noise, but I didn't find a way to reduce the contrast with that library. How can I do this?
You would need to rescale the difference to the mean value, here is an example, using this image as source. Extra code using PIL and imshow for visuals:
import numpy as np
import PIL.Image
import matplotlib.pyplot as plt
im = PIL.Image.open('a-600-600-image-of-a-building.jpg')
np_im = np.array(im)
np_mean = np.mean(np.array(im))
for factor in [1.0, 0.9, 0.5, 0.1]:
plt.figure()
plt.title("{}".format(factor))
reduced_contrast=(np_im-np_mean)*factor + np_mean
new_im = PIL.Image.fromarray(reduced_contrast)
plt.imshow(np.array(list(new_im.convert('RGBA').getdata())).reshape(new_im.height, new_im.width, 4))
plt.savefig("{}.png".format(factor))
Output:
The relevant line is reduced_contrast=(np_im-np_mean)*factor + np_mean

How to plot a 2D RGB colormap from array?

I am trying to plot a 2D colormap.
I would imagine something like this:
grid = np.ndarray([2,2])
grid[0,0] = [35,74,3]
grid[0,1] = [146,252,7]
grid[1,0] = [215,84,14]
grid[1,1] = [16,62,8]
plotter.map(grid)
What library supports this?
from PIL import Image
import random
import numpy as np
steps = 100
grid = np.ndarray([steps,steps,3])
for step_search_depth in range(steps):
for step_simulated_games_per_state in range(steps):
colour = random.randint(0,200)
grid[step_search_depth, step_simulated_games_per_state] = (colour,colour,colour)
Image.fromarray(grid, 'RGB').show()

Hough Transform on arrays of coordinates(Stock prices)

I want to apply Hough Transform on stock prices (array of numbers).
I read OpenCV and scikit-image docs and examples ,but got nothing how to apply the transformation to the arrays of numbers instead of images.
I created 2D array from data. First dimension is X(simply index of data) and second dimension is close prices.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pywt as wt
from skimage.transform import (hough_line, hough_line_peaks,probabilistic_hough_line)
from matplotlib import cm
path = "22-31May-100Tick.csv"
df = pd.read_csv(path)
y = df.Close.values
x = np.arange(0,len(y),1)
data = []
for i in x:
a = [i,y[i]]
data.append(a)
data = np.array(data)
How is it possible to apply the transformation with OpenCV or sickit-image?
Thank you

Kullback-Leibler divergence of the same image - scipy.stats.entropy

I was calculating kl distance between 3 images histograms:
import numpy as np
import scipy.misc
from skimage.io import ImageCollection, imread
from skimage import color
import skimage
from sklearn.datasets import load_sample_image
# all images in grayscale
lena = scipy.misc.lena().astype('uint8')
china = skimage.img_as_ubyte(color.rgb2grey( load_sample_image("china.jpg")) )
flower = skimage.img_as_ubyte(color.rgb2grey( load_sample_image("flower.jpg")) )
# histograms for all images
hist_lena, bin_edges_lena = np.histogram(lena, bins = range(256))
hist_china, bin_edges_china = np.histogram(china, bins = range(256))
hist_flower, bin_edges_flower = np.histogram(flower, bins = range(256))
When I use scipy.stats.entropy to compare the same image I've got different results:
# http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.stats.entropy.html
from scipy.stats import entropy
print entropy(pk=hist_lena, qk=hist_lena) # nan
print entropy(pk=hist_china, qk=hist_china) # -0.0
print entropy(pk=hist_flower, qk=hist_flower) # nan
I was expecting zero (unsigned?) as results.
Am I applying entropy function correctly?
Does it seem correct to apply this function on images histograms?

local histogram equalization

I am trying to use do some image analysis in python (I have to use python). I need to do both a global and local histogram equalization. The global version works well however the local version, using a 7x7 footprint, gives a very poor result.
This is the global version:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy import ndimage,misc
import scipy.io as io
from scipy.misc import toimage
import numpy as n
import pylab as py
from numpy import *
mat = io.loadmat('image.mat')
image=mat['imageD']
def histeq(im,nbr_bins=256):
#get image histogram
imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
cdf = imhist.cumsum() #cumulative distribution function
cdf = 0.6 * cdf / cdf[-1] #normalize
#use linear interpolation of cdf to find new pixel values
im2 = interp(im.flatten(),bins[:-1],cdf)
#returns image and cumulative histogram used to map
return im2.reshape(im.shape), cdf
im=image
im2,cdf = histeq(im)
To do the local version, I am trying to use a generic filter like so (using the same image as loaded previously):
def func(x):
cdf=[]
xhist,bins=histogram(x,256,normed=True)
cdf = xhist.cumsum()
cdf = 0.6 * cdf / cdf[-1]
im_out = interp(x,bins[:-1],cdf)
midval=interp(x[24],bins[:-1],cdf)
return midval
print im.shape
im3=ndimage.filters.generic_filter(im, func,size=im.shape,footprint=n.ones((7,7)))
Does anyone have any suggestions/thoughts as to why the second version will not work? I'm really stuck and any comments would be greatly appreciated! Thanks in advance!
You could use the scikit-image library to perform Global and Local Histogram Equalization. Stealing with pride from the link, below is the snippet. The equalization is done with a disk shaped kernel (or footprint), but you could change this to a square, by setting kernel = np.ones((N,M)).
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from skimage import data
from skimage.util import img_as_ubyte
from skimage import exposure
import skimage.morphology as morp
from skimage.filters import rank
# Original image
img = img_as_ubyte(data.moon())
# Global equalize
img_global = exposure.equalize_hist(img)
# Local Equalization, disk shape kernel
# Better contrast with disk kernel but could be different
kernel = morp.disk(30)
img_local = rank.equalize(img, selem=kernel)
fig, (ax_img, ax_global, ax_local) = plt.subplots(1, 3)
ax_img.imshow(img, cmap=plt.cm.gray)
ax_img.set_title('Low contrast image')
ax_img.set_axis_off()
ax_global.imshow(img_global, cmap=plt.cm.gray)
ax_global.set_title('Global equalization')
ax_global.set_axis_off()
ax_local.imshow(img_local, cmap=plt.cm.gray)
ax_local.set_title('Local equalization')
ax_local.set_axis_off()
plt.show()

Categories