My intention is to use matplotlib to convert a coloured image into a grayscale image and use colormap to display it in the Viridis scale.
The code for that is as follows:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
IMG = mpimg.imread('dog_1.jpg')
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
gray = rgb2gray(IMG)
plt.imshow(gray, cmap='viridis')
plt.show()
The output displayed is proper and as follows:
Output Image
Now, I want to save the output image in a variable as a numpy array to carry out further processing. Can I do it in any way?
plt.imread() returns a 3-dimensional numpy array with RGB layers. Your rgb2gray() function returns a 2-dimensional numpy array with a grayscale image. There is no need to extract a numpy array from the object returned by plt.imshow() when you have two numpy arrays with the image data already. However, if you insist in doing it, you can try the following:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
IMG = mpimg.imread('img.jpg')
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
gray = rgb2gray(IMG)
aximg = plt.imshow(gray, cmap='viridis')
# an array with RGBA data of the image produced by plt.imshow
arr = aximg.make_image(renderer=None, unsampled=True)[0]
Related
I need to make the pixels with the same intensity value in a list so I will get a list of lists of intensity values and each list has the pixels with the same intensity value.
import nibabel as nib
import numpy as np
from PIL import Image
import seaborn as sns
import matplotlib.pyplot as plt
from numpy import asarray
from scipy import ndimage, misc, stats
import cv2
### Load the image
img = nib.load('input_dir/FLAIR1.nii.gz')
img_data = img.get_fdata()
imgs = img_data[:, :, 23]
rows, col = imgs.shape
my_nlist = [[] for k in range(y.shape[0])]
print(im_arr[2,2])
for i in range(0, rows):
for j in range(0, col):
pixel = imgs[i, j]
for k in range(y.shape[0]):
if pixel == [k]:
my_nlist[k].append(pixel)
Don't make it harder on yourself than you have to :) this is exactly what a histogram is meant for!
import matplotlib.pyplot as plt
import cv2 as cv # You won't be needing cv2, it is just needed to create this example
img = cv.imread('dir/to/img', 0) # notice the grayscale flag
hist, bins, _ = plt.hist(img) # hist contains the list of pixels with the same intensity for each intensity in the picture
plt.show() # in case you want to visualize it
This is what it will look like:
I'm trying to convert a grayscale image's pixels into a numpy array.
Working on google colab.
it shows an error saying: TypeError: 'numpy.uint8' object is not iterable
enter code here
##load Library
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from google.colab import files
from scipy import misc #to see image
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from PIL import Image
pil_im = Image.open('papa.png')
pil_imgray = pil_im.convert('LA')
img = np.array(list(pil_imgray.getdata(band=0)), float)
img.shape = (pil_imgray.size[1], pil_imgray.size[0])
plt.imshow(img)
for eachRow in img:
for eachPixel in eachRow:
x_test.append(sum(eachPixel)/3.0)
You can directly load the image using matplotlib:
plt.imread('papa.png')
or you can convert your PIL image with:
img = np.asarray(pil_im)
Python: How to change a "penny" image color (copper) to different gray levels? Example given in image
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.clf()
p = plt.imread ('penny.jpg')
plt.imshow(p)
penny = p.copy()
The conversion to grayscale code comes from https://stackoverflow.com/a/12201744/1092820
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# Import the image
p = plt.imread('penny.png')
# Convert to grayscale
gray = np.dot(p[...,:3],[0.299, 0.587, 0.114])
# Round gray to nearest 1/n, where n is how many grays:
grayCount = 4
roundedGray = np.floor(gray * float(grayCount)) / float(grayCount)
# Display using matplotlib's copper color mapping
plt.imshow(roundedGray, cmap=plt.get_cmap('copper'))
plt.show()
I would like to create a black frame around an image. Unfortunately, I've got the following error.
ValueError: could not broadcast input array from shape (512,512) into shape (562,562)
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
import scipy as sc
import scipy.misc
im = sc.misc.ascent()
blackFrame= np.zeros((im.shape[0]+100,im.shape[1]+100))
blackFrame[50:,50:] = im[:,:]
plt.imshow(blackFrame, cmap="gray", vmin=0, vmax=250)
plt.show()
It works when I write blackFrame[100:,100:] = im[:,:] but it is not what I want.
This might help: blackFrame[50:50+im.shape[0],50:50+im.shape[1]] = im[:,:]
So I am trying to convert RGB TIF file to grayscale. This is the Python code
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import tifffile as tfl
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.587, 0.114])
imName = 'three_band/6120_2_0.tif'
im_rgb=tfl.imread(imName).transpose([1,2,0])
gray = rgb2gray(im_rgb)
plt.imshow(gray)
But when I try to view it using pyplot, I get a blue image like this
Can anyone point to what's wrong with my code?
Thanks.