I'm very new to coding and was coping this code from a youtube video I saw subbing in my own files for images when necessary. I got to the final step of testing the ai on new images and getting a result but this error message pops up.
dir_path = "/content/drive/MyDrive/darth_vader_Bing_images/test 1"
for i in os.listdir(dir_path ):
image = img.load_img(dir_path+'//'+ i)
plt.imshow(img)
plt.show
Sample code
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('cat1.jpeg')
plt.imshow(img)
Related
here is the part of my code
import PIL
import numpy as np
ramp = "$#B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,^`'."
def average(image):
im = np.array(image)
return np.average(im.flatten())
def convert(path, imgScale, fontScale):
if imgScale>1:
raise Exception('isnt right scale')
image = Image.open(path).convert("L")
W, H = image.size
I used to watch for any solutions. People say it is because of pil version. But i have the last one(https://i.stack.imgur.com/04mlK.png)
I need help with my code. I have built a recommendation system using cosine similarity on a colab and used pickle to serialized it. when I deserialized it inside a colab file, it works perfectly fine but when I deserialize it in a new colab file. it gives me an error
name 'data' is not defined
data is a variable that is initialized with my dataset which is outside of the class InstaPost.
import pandas as pd
import numpy as np
from sklearn.feature_extraction import text
from sklearn.metrics.pairwise import cosine_similarity
import dill as pickle
data = pd.read_csv("/content/instaData.txt")
data
data = data[["Caption", "Hashtags"]]
captions = data["Caption"].tolist()
uni_tfidf = text.TfidfVectorizer(input=captions, stop_words="english")
uni_matrix = uni_tfidf.fit_transform(captions)
uni_sim = cosine_similarity(uni_matrix)
def recommend_post(x):
return ", ".join(data["Caption"].loc[x.argsort()[-7:-1]])
data["Recommended Post"] = [recommend_post(x) for x in uni_sim]
class InstaPost:
def Post(number):
count = 0
wordy = (data["Recommended Post"][number])
sentence = wordy.split(',')
for i in sentence:
count=count+1
print(count," ",i)
obj = InstaPost
obj.Post(1)
pickle_out = open("modelREC", "wb")
pickle.dump(obj, pickle_out)
pickle_out.close()
pickle_in = open("modelREC", "rb")
exe = pickle.load(pickle_in)
print(exe.Post(10))
NOTE: on a different file
print(exe.Post)
works
and give output
<function InstaPost.Post at 0x7efc0b4c3f70>
if I need to give the reference of the data than please guide me how should I do it. It will be a great help to me
Thanks in advance
I have a script which uses the FuncAnimation routines in a loop to generate a lot of different animations which are saved in various directories. I'm working in Spyder, and every time an animation is generated, a .PNG image is displayed in the console.
Is there any way to NOT display the .PNG file with every animation? I'd like to turn off this image, since they will fill up my console in a long loop. When generating simple plots, it's easy to not display the image by just not calling plt.show. For animations, plt.show is called isn't called at all and the image still displays.
You can see that a .PNG image generated in the basic example:
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
line.set_data(data[..., :num])
return line,
# Fixing random state for reproducibility
np.random.seed(19680801)
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
fig = plt.figure()
data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
line_ani = animation.FuncAnimation(fig, update_line, 25, fargs=(data, l),
interval=50, blit=True)
line_ani.save('lines.mp4', writer=writer)
The .PNG image associated with the animation can be effectively hidden by calling plt.close(fig) after the animation is saved. This answer was inspired by a response by Demis to a similar question asking about simple plots instead of animations.
I am working on mnist_fashion data. The images in mnist_data are 28x28 pixel. For the purpose of feeding it to a neural network(multi-layer perceptron), I transformed the data into (784,) shape.
Further, I need to again reshape it back to the original size.
For this, I used below given code:-
from keras.datasets import fashion_mnist
import numpy as np
import matplotlib.pyplot as plt
(train_imgs,train_lbls), (test_imgs, test_lbls) = fashion_mnist.load_data()
plt.imshow(test_imgs[0].reshape(28,28))
no_of_test_imgs = test_imgs.shape[0]
test_imgs_trans = test_imgs.reshape(test_imgs.shape[1]*test_imgs.shape[2], no_of_test_imgs).T
plt.imshow(test_imgs_trans[0].reshape(28,28))
Unfortunately, I am not getting the similar image. I am not able to understand why this is happening.
expected image:
recieved image:
Kindly help me to resolve the problem.
pay attention when you flatten the images in test_imgs_trans
(train_imgs,train_lbls), (test_imgs, test_lbls) = tf.keras.datasets.fashion_mnist.load_data()
plt.imshow(test_imgs[0].reshape(28,28))
no_of_test_imgs = test_imgs.shape[0]
test_imgs_trans = test_imgs.reshape(no_of_test_imgs, test_imgs.shape[1]*test_imgs.shape[2])
plt.imshow(test_imgs_trans[0].reshape(28,28))
I'm working on pedestrian detection with a team. I am trying to figure out an error that keeps showing up that says "TypeError: samples is not a numpy array, neither a scalar" which when appear points to the line of code that is svm.train(X_data, cv2.ml.ROW_SAMPLE, labels12)
i tried following dozens of online guides but i still couldn't solve the problem, and im also very new to this
import cv2
import numpy as np
from skimage import feature
from skimage import exposure
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# training
X_data = []
labels1 = []
label = []
files = glob.glob ("new_pos_1/crop*.PNG")
for myFile in files:
# print(myFile)
image = cv2.imread(myFile,)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
X_data.append (image)
labels1.append('Pedestrian')
print('X_data shape:', np.array(X_data).shape)
labels12 = np.array([labels1])
print('labels12 shape:',np.array(labels12).shape)
print('labels shape:', np.array(labels1).shape)
#Testing
Y_data = []
files = glob.glob ("new_pos_1/person*.PNG")
for myFile in files:
# print(myFile)
image = cv2.imread (myFile)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Y_data.append (image)
label.append('Pedestrian')
print('Y_data shape:', np.array(Y_data).shape)
print('label shape:', np.array(label).shape)
hog_features = []
for image in np.array(X_data):
(fd, hogImage) = feature.hog(image, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2),
transform_sqrt=True, block_norm="L2-Hys", visualise=True)
hogImage = exposure.rescale_intensity(hogImage, out_range=(0, 255))
hogImage = hogImage.astype("uint8")
hog_features.append(fd)
print("I'm done hogging")
print(hog_features)
svm = cv2.ml.SVM_create()
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setType(cv2.ml.SVM_C_SVC)
svm.setC(2.67)
svm.setGamma(5.383)
print("Done initializing SVM parameters")
# Train SVM on training data
svm.train(X_data, cv2.ml.ROW_SAMPLE, labels12)
print("Done trainning")
svm.save('svm_data.dat')
print("SAVED.")
#testResponse = svm.predict(testData)[1].ravel()
cv2.waitKey(0)
The line at the beginning that says labels12 = np.array([labels1]) i used to try and fix the error that showed up to no avail.
This is the original website that helped me write this code: https://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial/
you should also do X_data2 = np.array([X_data]) and call svm.train(X_data2, cv2.ml.ROW_SAMPLE, labels12)