How numpy printoptions will work with images? - python

I was trying to print an image to analyze, if there are some changes in the pixel intensities if the images are forged. Anyways my doubt is related with the numpy.printoptions.
I was trying below code and numpy.printoptions was not working:
Image of code snippet
Code:
import numpy
import numpy as np
DIR = "D:/Work/ML/API/MNB/28 - Forgery/data/phase-01-training.tar/dataset-dist/chunks/1500_64_16"
TRAIN_CHUNKS = os.path.join(DIR, "train")
TRAIN_FAKE_CHUNKS = os.path.join(TRAIN_CHUNKS, "fake")
TRAIN_PRISTINE_CHUNKS = os.path.join(TRAIN_CHUNKS, "pristine")
IND=2000
train_chunk_files = os.listdir(TRAIN_FAKE_CHUNKS)
src = cv2.imread(os.path.join(TRAIN_FAKE_CHUNKS, train_chunk_files[IND]))
print(src[:, :, 1].shape)
with numpy.printoptions(threshold=64):
ok = np.copy(src[:, :, 1])
print(ok)
# print(src[:, :, 1])
plt.imshow(src)
plt.show()
But on the other end numpy printoptions is working fine for mnist dataset!!!
Working code snippet
code:
import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
import numpy as np
np.set_printoptions(linewidth=200)
import matplotlib.pyplot as plt
print(type(training_images[0]))
plt.imshow(training_images[0])
print(training_labels[0])
print(training_images[0])
What is the mistake I am doing over here? How to print the RGB image for each channel? I have checked the datatype for both of the image, it is numpy, ndarray.
Edit 1:
Things are not working by using linewidth.
Code with linewidth in np.printoptions

From the diagram you have given in "Image of code snippet" link, it seems printoptions print the values in both cases, incase if the values needs to be printed properly (displaying all values), u could use,
with np.printoptions(linewidth=200):
ok = np.copy(src[:, :, 1])
print(ok)
if this is not what you are looking for, please let me know in the comments section. Happy to correct the answer!

Related

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

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.

Replacing zero elements in my image array on python

I am training my model with several images.
When training my model I realized that I could increase my accuracy by replacing the zero elements in my image array with other values and so I replaced them with the median value of my image as shown with the following code.
import cv2
import imutils
import numpy as np
r_val_all = np.zeros((2000,112,112))
for r in range(len(r_val)):
#LOAD IMAGES
r_image_v = cv2.imread(r_val[r])
r_gray_v = cv2.cvtColor(r_image_v, cv2.COLOR_BGR2GRAY)
r_gray_v = imutils.resize(r_gray_v, width=112, height=112)
n = np.median(r_gray_v[r_gray_v > 0])
r_gray_v[r_gray_v == 0] = n
r_val_all[r,:,:] = r_gray_v
The accuracy did improve however it is not quite there yet.
What I actually require is something where the zero elements are replaced with a continuation of the pre-existent array values.
However I was not sure how to tackle such a problem are there any tools that perform the operation I require?
I used the second answer from the link, tell me if this is close to what you want, because it appeared to be what you wanted.
Creating one sample image and center it, so it's somewhat close to your first example image.
import numpy as np
import matplotlib.pyplot as plt
image = np.zeros((100, 100))
center_noise = np.random.normal(loc=10, size=(50, 50))
image[25:75, 25:75] = center_noise
plt.imshow(image, cmap='gray')
Inspired by rr_gray = np.where(rr_gray==0, np.nan, rr_gray) #convert zero elements to nan in your code, I'm replacing the zeros with NaN.
image_centered = np.where(image == 0, np.nan, image)
plt.imshow(image_centered, cmap='gray')
Now I used the function in the second answer of the link, fill.
test = fill(image_centered)
plt.imshow(test, cmap='gray')
This is the result
I'm sorry I can't help you more. I wish I could, I'm just not very well versed in image processing. I looked at your code and couldn't figure out why it's not working, sorry.

how to convert image to dataset to process machine learning

How to convert a image to datasets or numpy array and to predict by fiting it to clf
import PIL as pillow
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
infilename=input()
im=Image.open(infilename)
imarr=np.array(im)
flatim=imarr.flatten('F')
clf=svm.SVC(gamma=0.0001,C=100)
x,y=im.size
#how to fit the numpy array to clf
clf.fit(flatim[:-1],flatim[:-1])
print("prediction:",clf.predict(flatim[-1]))
plt.imshow(flatim,camp=plt.cm.gray_r,interpolation='nearest')
plt.show()
Anyone please and thanks!!!
there is no other reason of using SVM on a single image except for fun of doing it. Here are the fixes I did. 1) use .convert("L") to convert the image as 2D array grayscale. 2) created a dummy target variable y as randomized 1D array. 3) fix type error displaying the image again (plt.imshow) cmap (instead of camp) and im (instead of flatim)
import PIL as pillow
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
im=Image.open("sample.jpg").convert("L")
imarr=np.array(im)
flatim=imarr.flatten('F')
clf=svm.SVC()
#X,y=im.size
X = imarr
y = np.random.randint(2, size=imarr.shape[0])
clf.fit(X, y)
#how to fit the numpy array to clf
#clf.fit(flatim[:-1],flatim[:-1])
# I HAVE NO IDEA WHAT I"M DOING HERE!
print("prediction:", clf.predict(X[-2:-1]))
plt.imshow(im,cmap=plt.cm.gray_r,interpolation='nearest')
plt.show()
I see a good example in scikit-learn website of using SVM. I guess this is what you are trying to copy. Isn't?

How to generate the same image with the function of imshow() from matplotlib(python) and imshow() in matlab?

For the same matrix, the image generated by the function imshow() from matplotlib and matlab is different. how to change some parameters of imshow() in matplotlib can get same result in matlab
%matlab
img = 255*rand(101);
img(:,1:50)=3;
img(:,52:101)=1;
img(:,51)=2;
trans_img=imtranslate(img,[3*cos(pi/3),3*sin(pi/3)]);
imshow(trans_img)
This is an image generated by matlab
#python
import numpy as np
import matplotlib.pyplot as plt
from mlab.releases import latest_release as mtl #call matlab function
img = 255 * np.random.uniform(0, 1, (101, 101))
img[:, 51:101] = 1
img[:, 0:50] = 3
img[:, 50] = 2
trans_img = mtl.imtranslate(img, [[3*math.cos(math.pi/3),3*math.sin(math.pi/3)]]
i = plt.imshow(trans_img, cmap=plt.cm.gray)
plt.show(i)
This is an image generated by matplotlib
The trans_img matrix is the same in both cases, but the images in matlab and python are different
Unfortunately I don't have an up-to-date enough version of Matlab that has the imtranslate function, but thankfully the image package in Octave does, which I'm sure is equivalent. Equally, I will be using the oct2py module instead of mlab as a result, for python to access the imtranslate function from octave within python.
Octave code:
img = 255*rand(101);
img(:,1:50)=3;
img(:,52:101)=1;
img(:,51)=2;
trans_img = imtranslate(img, 3*cos(pi/3),3*sin(pi/3));
imshow(trans_img, [min(trans_img(:)), max(trans_img(:))])
Python code:
import numpy as np
import matplotlib.pyplot as plt
import math
from oct2py import octave
octave.pkg('load','image'); # load image pkg for access to 'imtranslate'
img = 255 * np.random.uniform(0, 1, (101, 101))
img[:, 51:101] = 1
img[:, 0:50] = 3
img[:, 50] = 2
trans_img = octave.imtranslate(img, 3*math.cos(math.pi/3), 3*math.sin(math.pi/3))
i = plt.imshow(trans_img, cmap=plt.cm.gray)
plt.show(i)
Resulting image (identical) in both cases:
My only comment on why you may have been seeing the discrepancy, is that I did specify the min and max values in imshow, to ensure appropriate intensity scaling. Equally you could have just used imagesc(trans_img) instead (I actually prefer this). I didn't specify such limits explicitly in python for plt.imshow ... perhaps it performs scaling by default.
Also, your code has a small bug; in the octave version of imtranslate at least, the function takes 3 arguments, not two. (Also, your original code has an unbalanced bracket).

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