camera-classifier
camera-classifier copied to clipboard
ValueError: cannot reshape array of size 16950 into shape (16800,)
I am getting error at reshaping the image: in model.py
img = img.reshape(16800) ^^^^^^^^^^^^^^^^^^ ValueError: cannot reshape array of size 16950 into shape (16800,)
To resolve this issue, you need to ensure that the total number of elements in the array matches the total number of elements in the desired shape. In this specific case, it seems like you want to reshape an array with 16950 elements into a shape of (16800,). Since these numbers don't match, you will need to reshape it into a shape that has the same number of elements (in this case, 16950).
You can reshape the array into a shape of (16950,) like this:
img = img.reshape(16950)
Make sure that the new shape you specify matches the total number of elements in the array you are trying to reshape.
# sure you cannot directly (16800,) to (16950,) due 16800 !=16950 you can reshape it to (16800,1), to (1, 16800)
#(numpy.tranpose()) , in machine learning you can reshape that through padding slicing, cliping , ....(arrays represents data #such images , text etc)
import numpy as np
# convert it an array
arr = np.arange(16800)
# Calculate padding amount
padding_amount = 16950 - arr.shape[0]
# Pad with zeros at the end
padded_arr = np.pad(arr, (0, padding_amount), mode='constant', constant_values=0)
# Reshape to the desired shape
reshaped_arr = padded_arr.reshape(16950,)
print(reshaped_arr.shape) # Output: (16950,)
#you can use other libraries opencv, keras, tensorflow, pytorch
use the below code in model.py to resolve this issue
from sklearn.svm import LinearSVC import numpy as np import cv2 as cv from PIL import Image
class Model:
def __init__(self):
self.model = LinearSVC()
def train_model(self, counters):
img_list = []
class_list = []
for i in range(1, counters[0]):
img = cv.imread(f'1/frame{i}.jpg', cv.IMREAD_GRAYSCALE)
img = cv.resize(img, (120, 140))
img = img.reshape(16800)
img_list.append(img)
class_list.append(1)
for i in range(1, counters[1]):
img = cv.imread(f'2/frame{i}.jpg', cv.IMREAD_GRAYSCALE)
img = cv.resize(img, (120, 140))
img = img.reshape(16800)
img_list.append(img)
class_list.append(2)
img_list = np.array(img_list)
class_list = np.array(class_list)
self.model.fit(img_list, class_list)
print("Model successfully trained!")
def predict(self, frame):
frame = frame[1]
cv.imwrite("frame.jpg", cv.cvtColor(frame, cv.COLOR_RGB2GRAY))
img = Image.open("frame.jpg")
img = img.resize((120, 140))
img.save("frame.jpg")
img = cv.imread('frame.jpg', cv.IMREAD_GRAYSCALE)
img = img.reshape(16800)
prediction = self.model.predict([img])
return prediction[0]