import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
pic = Image.open('mountain1.jpg')
pic_array = np.asarray(pic)
# plt.imshow(pic_array[:,:,2], cmap='gray')
pic_array[:,:,2]=0
plt.imgshow(pic_array)
plt.show()
i get the following error/ pic_array[:,:,2]=0
ValueError: assignment destination is read-only How do i edit the array?
The problem is that in the code the original image and the numpy array share the same memory. hence the read-only error when you try to update the array.
Create the copy as the original array and it should be fine.
Another small thing that I noticed is plt.imgshow(image) is used instead of plt.imshow(image).
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
pic = Image.open('mountain1.jpg')
# copy of the numpy array so that the original image is not changed.
pic_array = np.asarray(pic).copy()
pic_array[:,:,2]=0
plt.imshow(pic_array)
Cheers!
Related
I'm new to python! I am trying to upgrade myself. However, I have a dataset namely tree_dataset which contains 3 folders i.e. test, train, and validation. Each folder contains 9 different folders (classes). Now, I want to show a sample of all first images (data) from the 9 different classes.
My code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set(style="whitegrid")
import os
import imageio
import skimage
import skimage.io
import skimage.transform
# Showing sample of all first images (data) from the 09 different classes
f, ax = plt.subplots(nrows=1,ncols=9, figsize=(20, 10))
i=0
for d in directory:
file='/content/tree_dataset'+d+'/1.png'
im=imageio.imread(file)
ax[i].imshow(im,resample=True)
ax[i].set_title(d, fontsize=8)
i+=1
Error: FileNotFoundError: No such file: '/content/Weeds_Detectiontrain/1.png'
I have 6 different images. I want to store them together in a single numpy array. Is that possible? If yes, how can I do that?
from PIL import Image
from matplotlib import image
import matplotlib.pyplot as plt
from os import listdir
from numpy import asarray
import numpy as np
for i in range(1,6):
image=Image.open(str(i)+'.jpg')
image=image.resize((100,100))
temp=asarray(image)
print(np.append(X_train,temp,axis=0))
This raises the following Exception:
ValueError: all the input arrays must have same number of dimensions
you can create a list of arrays and the convert back to numpy array
list_of_pics = list()
for i in range(1,6):
image=Image.open(str(i)+'.jpg')
image=image.resize((100,100))
list_of_pics.append(np.asarray(image))
new_array = np.array(list_of_pics)
the final dimentions of new_array should be (6,100,100)
"Why is plt.imshow (image) only getting output when written in last? How do I show output for all written plt.imshow (image)?I am unable to get all the output where i have used this plt.imshow(image)"
import os.path
from skimage.io import imread
from skimage import data_dir
import numpy as np
img=imread(os.path.join(data_dir,'astronaut.png'))
plt.imshow(img)
#1. image slicing from the original image
img_slice=img.copy()
img_slice=img_slice[0:300,360:480]
plt.imshow(img_slice)
img_slice[np.greater_equal(img_slice[:,:,0],100) & np.less_equal(img_slice[:,:,0],150)]=0
plt.imshow(img_slice)
# Fix the new rocket image back to its place in the original image.
img[0:300,360:480,:]=img_slice
plt.imshow(img)
"I am only getting the image for the last written plt.imshow(img). I am unable to get all the images as the output for the written plt.imshow()"
Just add plt.show() after your plt.imshow() calls!
Also, try to provide the exact same code you are using. Your code snippet doesn't have imports for plt.
Anyways, For reference,
import os.path
from skimage.io import imread
from skimage import data_dir
import numpy as np
import matplotlib.pyplot as plt
data_dir = '/some/directory/'
img=imread(os.path.join(data_dir,'astronaut.png'))
plt.imshow(img)
plt.show()
#1. image slicing from the original image
img_slice=img.copy()
img_slice=img_slice[0:300,360:480]
plt.imshow(img_slice)
plt.show()
img_slice[np.greater_equal(img_slice[:,:,0],100) & np.less_equal(img_slice[:,:,0],150)]=0
plt.imshow(img_slice)
plt.show()
# Fix the new rocket image back to its place in the original image.
img[0:300,360:480,:]=img_slice
plt.imshow(img)
plt.show()
I am new using python and try to do some plots. I realized, that a plot of a bump function is incorrect. I have no idea how python came to this result.
This is my 'code'
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
class MainBody():
x = np.linspace(0.0001,99.9999,1000)
result = np.exp((-1.0)/(x*(100.0-x)))
plt.plot(x,result)
plt.show()
I got this result
but I should get this
I know that Python is powerful but I think such simple things should work without occuring such errors, where is my mistake?
Thank you
Matthias
Use plt.ylim to set the y-limits. Otherwise, by default, matplotlib will try to show the entire dataset, whose y-limits go roughly from 0 to 1:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.0001,99.9999,1000)
result = np.exp((-1.0)/(x*(100.0-x)))
plt.plot(x,result)
plt.ylim(0.9975, 0.9999)
plt.show()
Given the following data frame and line graph:
import matplotlib.pyplot as plt
from cycler import cycler
import numpy as np
fig, ax=plt.subplots(1)
d=pd.DataFrame({'a':[1,2,3,4],
'b':[2,3,4,5],
'c':[3,4,5,6]})
colors=['r','g','b']
ax.set_prop_cycle(cycler('color', [colors]))
ax.plot(d[:3],'-ko',d[2:],'--ko')
plt.show()
You'll notice that I am trying to assign one color per line but it is not working. I also tried using the colors argument in ax.plot.
It seems like this should be straight forward.
Thanks in advance for any help on this.
There are two problems in your code.
the 'k' in '-ko' and '--ko' sets the colour to black, so we need to remove that
colors is already a list, but you have put it inside square brackets again in the call to set_prop_cycle, and thus made it into a nested list: [['r','g','b']]. Remove the square brackets there and it all works fine: ax.set_prop_cycle(cycler('color', colors))
So, your code will look like:
import matplotlib.pyplot as plt
import pandas as pd
from cycler import cycler
import numpy as np
fig, ax=plt.subplots(1)
d=pd.DataFrame({'a':[1,2,3,4],
'b':[2,3,4,5],
'c':[3,4,5,6]})
colors=['r','g','b']
ax.set_prop_cycle(cycler('color', colors))
ax.plot(d[:3],'-o',d[2:],'--o')
plt.show()