I want to implement PCA (Principal Component Analysis) to get an RGB version on an image . I'm opening the images from a github repository . I found a very helpful similar question here (Reverse generation of RGB PCA image not working)
and implement it , with the right corrections , but still getting the error:
line 22, in <module>
img_reshaped = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2]))
AttributeError: 'JpegImageFile' object has no attribute 'shape'
Here's my code :
from PIL import Image
import requests
from io import BytesIO
import pylab as plt
import numpy as np
#url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image1.jpg'
url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image2.jpg'
# url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image3.jpg'
# url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image4.jpg'
# url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image5.jpg'
response = requests.get(url)
img = Image.open(BytesIO(response.content))
plt.axis('off')
plt.imshow(img)
img.show()
img_reshaped = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2]))
print(img_reshaped.shape)
from sklearn.decomposition import PCA
pca = PCA(n_components=3)
pca.fit(img_reshaped)
img_transformed = pca.transform(img_reshaped)
print(img_transformed.shape)
img_inverse = pca.inverse_transform(img_transformed)
print(img_inverse.shape)
plt.imshow(img_inverse)
plt.show()
img_inverse_reshaped = np.reshape(img_inverse, img.shape)
print(img_inverse.shape)
plt.axis('off')
plt.imshow(img_inverse_reshaped)
plt.show()
Related
i am trying to convert nrrd file into jpg by reading that nrrd image using pynrrd and then using the pixel i am trying to form an image but the out i am getting is terrible contrast image. Below is waht i have tried
import numpy as np
import nrrd
from PIL import Image
import numpy as np
filename = "/content/drive/MyDrive/CT.nrrd"
readdata, header = nrrd.read(filename)
print(readdata.shape) # (512, 512, 504)
for i in range(504):
if i == 200:
img = np.array(readdata[:,:,i])
print(img.shape)
print(np.amax(img))
img = (np.maximum(img, 0) / img.max()) * 255.0
img = Image.fromarray(np.uint8(img), mode = "L")
img.save(f'/content/testrgb{i}.png')
break
The output i am getting is this
Can someone please help me this
from PIL import Image
import numpy as np
import nrrd
def manipulating_nrrd_contrast(img, level):
img_c = img.astype(int).copy()
factor = (8 * (level+255)) / (255 * (259-level)) #This 8 here is the value that i changes manually by try and test and found out that this works best
img_c = factor * (img_c - 128) + 128
img_c = np.clip(img_c, 0, 255)
return img_c.astype(np.uint8)
filename = "/content/drive/MyDrive/CT.nrrd"
readdata, header = nrrd.read(filename)
tag_info = get_meta_data(header)
print(tag_info)
print(readdata.shape)
for i in range(readdata.shape[2]):
b = np.asarray(readdata[:,:,i]).astype(int)
final = Image.fromarray(manipulating_nrrd_contrast(b, 128))
final.save(f'/content/png/testrgb{i}.png')
And, The Result that i got is below
Actually, I was working on a guided project on (neural style transfer) in which I came across the concept of preprocessing and then deprocessing of the image. It will be great if anyone can help me in understanding this concept.
from torchvision import transforms as T
def preprocess(img_path,max_size = 500):
image = Image.open(img_path).convert('RGB')
if max(image.size) > max_size:
size = max_size
else:
size = max(image.size)
img_transform = T.Compose([
T.Resize(size),
T.ToTensor(),
T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
image = img_transform(image)
image = image.unsqueeze(0)
return image
....
# Deprocess image
import numpy as np
import matplotlib.pyplot as plt
def deprocess(tensor):
image = tensor.to('cpu').clone()
image = image.numpy()
image = image.squeeze(0) #(1,3,224,224) -> (3,224,224)
image = image.transpose(1,2,0) #(3,224,224) -> (224,224,3)
image = image*np.array([0.229, 0.224,0.225])+np.array([0.485,0.456,0.406])
image = image.clip(0,1)
return image
content_d = deprocess(content_p)
style_d = deprocess(style_p)
print("Deprecess content :",content_d.shape)
print("Deprocess style :",style_d.shape)
fig, (ax1,ax2) = plt.subplots(1,2,figsize = (20,10))
ax1.imshow(content_d)
ax2.imshow(style_d)
Code Image for preprocessing
Code Image for deprocessing
I would like to know that can we perform further computation of image by just preprocessed image without actually deprocessing it ?
I have used VGG16 and imagenet weights to predict an image. But unfortunately, the prediction was wrong.
I don't know where I went wrong.
Code:
from keras.preprocessing import image as image_util
from keras.applications.imagenet_utils import preprocess_input
from keras.applications.imagenet_utils import decode_predictions
from keras.applications import VGG16
import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image",required= True,help ="path of the image")
args = vars(ap.parse_args())
# orig = cv2.imread(args["image"]) #Opencv function to load a image
image = image_util.load_img(args["image"],target_size=(224,224))
image = image_util.img_to_array(image)
#print("!!!!!.....!!!!")
print(image.shape)
image = np.expand_dims(image,axis=0) #(224,224,3) --> (1,224,224,3)
#print("!!!!!.....!!!!")
print(image.shape)
image = preprocess_input(image)
#Loading the model
model = VGG16(weights="imagenet")
pred = model.predict(image)
#print("111!!!!!.....!!!!")
#print(pred)
p = decode_predictions(pred)
#print("222!!!!!.....!!!!")
#print(p)
for (i,(imagenetID,label,prob)) in enumerate(p[0]):
print("{}. {}: {:.2f}%".format(i+1, label, prob*100))
orig = cv2.imread(args["image"]) #Opencv function to load a image
(imagenetID,label,prob) = p[0][0]
cv2.putText(orig, "Label:{},{:.2f}%".format(label,prob*100),(10,30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,255,0),2)
cv2.imshow("classification",orig)
cv2.waitKey(0)
Output:
The output must be an apple. But I got Granny smith
I have problem with preprocessing data set for deep learning.
I am using U-net.
I have training data, label data, test data size of 512x512.
I want patch based learning so i am trying to change 512x512 slices to multiple 64x64 slices so that I can train image with 64x64 patches. In my case I want to make 64x64 patches stride 32 pixel from original 512x512 Images.
For example, first patch is formed from (0,0) ~ (64,64) and the next patch is formed from (32,0) ~ (64 + 32, 64)
This is full code of data.py
#from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import numpy as np
import os
import glob
import cv2
from os.path import *
#from libtiff import TIFF
import matplotlib.pyplot as plt
class dataProcess(object):
def __init__(self, out_rows, out_cols):
"""
"""
self.out_rows = out_rows
self.out_cols = out_cols
def load_train_data(self):
imgs_row, imgs_col = 512,512
train_list = []
train_img = []
label_list = []
label_img = []
train_path = 'C:\\Users\\Lee Doyle\\unet\\data\\Train'
label_path = 'C:\\Users\\Lee Doyle\\unet\\data\\Label'
######################Traindata################################
print('-' * 30)
print('load train images...')
print('-' * 30)
for i in glob.glob(train_path + '/*.[tT][iI][fF]'):
train_list.append(abspath(i))
print(len(train_list))
for i in train_list:
# print(i)
img = cv2.imread(i, cv2.IMREAD_GRAYSCALE)
train_img.append(img.astype(np.float32)/255.0)
train_img = np.array(train_img)
print(train_img)
######################Labeldata################################
for i in glob.glob(label_path + '/*.[tT][iI][fF]'):
label_list.append(abspath(i))
for i in label_list:
img = cv2.imread(i, cv2.IMREAD_GRAYSCALE)
label_img.append(img.astype(np.float32) / 255.0)
label_img = np.array(label_img)
fig = plt.figure()
a=fig.add_subplot(1,2,1)
plt.imshow(train_img[0],cmap='gray')
a.set_title('trian image')
a=fig.add_subplot(1,2,2)
plt.imshow(label_img[0]+train_img[0],cmap='gray')
plt.imshow(label_img[0],cmap='gray')
a.set_title('Image with GT SEG ')
plt.show()
print(train_img.shape)
train_img = train_img.reshape(train_img.shape[0], imgs_row, imgs_col, 1)
label_img = label_img.reshape(label_img.shape[0], imgs_row, imgs_col, 1)
return train_img,label_img
def load_test_data(self):
imgs_row, imgs_col = 512,512
test_list = []
test_img = []
test_path = 'C:\\Users\\Lee Doyle\\unet\\data\\Test'
######################Testdata#################################
print('-' * 30)
print('load test images...')
print('-' * 30)
for i in glob.glob(test_path + '/*.[tT][iI][fF]'):
test_list.append(abspath(i))
for i in test_list:
img = cv2.imread(i, cv2.IMREAD_GRAYSCALE)
# img=cv2.resize(img,(512,512))
test_img.append(img.astype(np.float32) / 255.0)
test_img = np.array(test_img)
# mean = test_img.mean(axis=0)
# test_img -= mean
test_img=test_img.reshape(test_img.shape[0],imgs_row,imgs_col,1)
print(test_img.shape)
return test_img
if __name__ == "__main__":
mydata = dataProcess(512,512)
mydata.load_train_data()
mydata.load_test_data()
I think I need to add patch making code near this code.
for i in glob.glob(train_path + '/*.[tT][iI][fF]'):
train_list.append(abspath(i))
print(len(train_list))
for i in train_list:
# print(i)
img = cv2.imread(i, cv2.IMREAD_GRAYSCALE)
train_img.append(img.astype(np.float32)/255.0)
train_img = np.array(train_img)
print(train_img)
I apppreciate your help.
import numpy as np
import cv2
import scipy.misc, math
from scipy.misc.pilutil import Image
while True:
img = Image.open('img.jpg').convert(L)
img1 = scipy.misc.fromimage(img)
f1 = img1.flatten()
hist,bins = np.histogram(img1, 256,[0,255])
cdf = hist.cumsum
cdf_m = np.ma.masked_equal(cdf,0)
cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
cdf = np.ma.filled(cdf_m,0)
im2 = cdf[f1]
im3 = np.reshape(im2,img1.shape)
im4 = scipy.misc.toimage(img3)
im4.show()
I am trying to histogram equalize an image. When i run the program, neither an output image is displayed nor an error is shown.
Can anyone tell me where am going wrong
Try:
import numpy as np
import cv2
import scipy.misc, math
from scipy.misc.pilutil import Image
while True:
img = Image.open('img.jpg').convert(L)
img1 = scipy.misc.fromimage(img)
f1 = img1.flatten()
hist,bins = np.histogram(img1, 256,[0,255])
cdf = hist.cumsum
cdf_m = np.ma.masked_equal(cdf,0)
cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
cdf = np.ma.filled(cdf_m,0)
im2 = cdf[f1]
im3 = np.reshape(im2,img1.shape)
im4 = scipy.misc.toimage(im3)
im4.format = "PNG" # out of paranoia mainly
im4.show()