custom DMatch object for NNDR type error? - image-stitching

d1,d2 are descriptor
matches=[]
for i in range(len(d1)-1):
dist= (np.linalg.norm(d1[i] - d2[i])) / (np.linalg.norm(d1[i] - d2[i+1]))
#print (dist," ")
if dist <= 0.8:
k=k+1
matches.extend(cv2.DMatch(i,i,dist))
img3 = cv2.drawMatchesKnn(img1, f1, img2, f2,matches, None, flags=2)
TypeError: 'cv2.DMatch' object is not iterable
Any help?

Solved by following changing
matches.append(cv2.DMatch(i,i,dist)) but following is not working
img3 = cv2.drawMatchesKnn(img1, f1, img2, f2,matches, None, flags=2)

Related

How to print prediction by category inside a loop

I'm having a problem with printing pictures with labels of prediction in my project.
i = 1
for image in DATADIR:
prediction = model.predict
([prepare(r'MY_DIR\manual_testing\{}.jpg'.format(i))])
img = mpimg.imread(r'MY_DIR\manual_testing\{}.jpg'.format(i))
imgplot = plt.imshow(img)
plt.show()
print(CATEGORIES[int(prediction[0][0])])
i += 1
Here MY_DIR replaces the actual directory.
I'm having the following error: TypeError: 'method' object is not subscriptable
I don't really understand what should be changed. If I try to put print('Hello world') in the for loop everything is working.
p.s. If you have an example of how to make the output look more beautiful you are welcome.
Thank you in advance.
I found the solution:
i = 1
for item in os.listdir(DATADIR):
prediction = model.predict([prepare(r'MY_DIR\manual_testing\{}.jpg'.format(i))])
img = mpimg.imread(r'MY_DIR\manual_testing\{}.jpg'.format(i))
imgplot = plt.imshow(img)
plt.show()
print(CATEGORIES[int(prediction[0][0])])
i += 1

How to apply a function to convert the paths to arrays using cv2 in tensorflow data pipeline?

Any help will be highly appreciated
I'm trying to load two lists containing image paths and their corresponding labels. Something like this:
p0 = ['a','b',....] #paths to images .tif format
p1 = [1,2,3,......] #paths to images .tif format
labels = [0,1,1,...] #corresponding labels w.r.t both the lists
I used a tf.data in the following way:
def TFData(p_0, p_1, batch_size, labels=None, is_train=True):
dset = tf.data.Dataset.from_tensor_slices((p_0,p_1))
if labels is not None:
label = tf.data.Dataset.from_tensor_slices(labels)
AUTO = tf.data.experimental.AUTOTUNE
final_dset = tf.data.Dataset.zip((dset, label))
final_dset = final_dset.batch(batch_size, drop_remainder=is_train).prefetch(AUTO)
return final_dset
This returns:
<PrefetchDataset shapes: (((64,), (64,)), (64,)), types: ((tf.string, tf.string), tf.int32)>
My question is how to apply a function to convert the paths to arrays using cv2 as the images are .tif files? such that the result will be:
<PrefetchDataset shapes: (((64,256,256,3), (64,256,256,3)), (64,)), types: ((tf.float64, tf.float64), tf.int32)>
I'm using a dataset.map. However it's throwing error:
def to_array(p_0):
im_1 = cv2.imread(p_0,1)
#im = tfio.experimental.image.decode_tiff(paths)
im_1 = cv2.resize(im_1,(img_w,img_h)) #img_w=img_h=256
im_1 = np.asarray(im_1, dtype=np.float64)
im_1 /= 255
return im_1
def parse_fn(p_0):
[p_0,] = tf.py_function(to_array, [p_0], [tf.float64])
return p_0
def TFData(p_0, p_1, batch_size, labels=None, is_train=True):
dset_1 = tf.data.Dataset.from_tensor_slices(p_0)
dset_1 = dset_1.map(parse_fn)
dset_2 = tf.data.Dataset.from_tensor_slices(p_1)
dset_2 = dset_2.map(parse_fn)
if labels is not None:
label = tf.data.Dataset.from_tensor_slices(labels)
AUTO = tf.data.experimental.AUTOTUNE
final_dset = tf.data.Dataset.zip((dset_1, dset_2, label))
final_dset = final_dset.batch(batch_size, drop_remainder=is_train).prefetch(AUTO)
return final_dset
print(train_data) #where train_data is defined as TFData()
<PrefetchDataset shapes: ((<unknown>, <unknown>), (64,)), types: ((tf.float64, tf.float64), tf.int32)>
This throws an error:
for (t,p),l in train_data.as_numpy_iterator():
print(t)
print(p)
print(l)
print(type(t))
break
SystemError: <built-in function imread> returned NULL without setting an error
[[{{node EagerPyFunc}}]] [Op:IteratorGetNext]
Any help will be highly appreciated
I think your problem is in cv2.imread.
Have you checked outside the functions to see if it is reading and plotting the data accordingly?
Please, try with -1 instead:
im_1 = cv2.imread(p_0,-1)

How to solve TypeError: Expected Ptr<cv::UMat> for argument 'img'?

i get this following error
TypeError: Expected Ptr<cv::UMat> for argument 'img'
Here is my code
def draw_homography_points(img, x, resize=256, color=(255,0,0)):
y_start1 = (0.3+x[2])*(resize-1)
y_start = 0.3*(resize-1)
y_stop = resize-1
src = np.float32([[0.45*(2*resize-1),y_start],[0.55*(2*resize-1), y_start],[0.1*(2*resize-1),y_stop],[0.9*(2*resize-1), y_stop]])
dst = np.float32([[(0.45+x[0])*(2*resize-1), y_start1],[(0.55+x[1])*(2*resize-1), y_start1],[(0.45+x[0])*(2*resize-1), y_stop],[(0.55+x[1])*(2*resize-1),y_stop]])
dst_ideal = np.float32([[0.45*(2*resize-1), y_start],[0.55*(2*resize-1), y_start],[0.45*(2*resize-1), y_stop],[0.55*(2*resize-1),y_stop]])
[cv2.circle(np.assarray(img), tuple(idx), radius=5, thickness=-1, color=(255,0,0)) for idx in src]
[cv2.circle(np.assarray(img), tuple(idx), radius=5, thickness=-1, color=(0,255,0)) for idx in dst_ideal]
[cv2.circle(np.assarray(img), tuple(idx), radius=5, thickness=-1, color=(0,0,255)) for idx in dst]
return img
the error occur on the last 4 line [cv2.circle....]
i try to change cv2.circle(np.assarray(img) into cv2.circle(np.float32(img) but the problem is not solved. Does anyone have an idea?

'numpy.ndarray' object has no attribute 'predict'

I've finished modelling the forecasting on my training data. Now I want to plot a forecast with the function 'predict' to evaluate it with my test data. But my code does not work
I received the error as follows
File "", line 1, in
Fcast = predictions_ARIMA.values.predict(start = '11/08/2019', end = '22/09/2019')
AttributeError: 'numpy.ndarray' object has no attribute 'predict'
Could you please help me?
Thanks so much !!!
#modelling
model = ARIMA(ts_log, order=(1, 1, 1))
results_ARIMA= model.fit(disp=-1)
plt.plot(ts_log_diff)
plt.plot(results_ARIMA.fittedvalues, color='red')
plt.title('RSS: %.4f'% sum((results_MA.fittedvalues-ts_log_diff)**2))
plt.title('Fitting data _ MSE: %.2f'% ((
(results_MA.fittedvalues-ts_log_diff)**2).mean()))
plt.xlabel('Date')
plt.legend(('Real Log Values', 'Predicted Log Values'), loc='lower right')
predictions_ARIMA_diff = pd.Series(results_ARIMA.fittedvalues, copy=True)
print (predictions_ARIMA_diff.head())
predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum()
print (predictions_ARIMA_diff_cumsum.head())
predictions_ARIMA_log = pd.Series(ts_log.ix[0], index=ts_log.index)
predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_ARIMA_diff_cumsum,
fill_value=0)
predictions_ARIMA_log.head(20)
def mean_sqared_err(y,yhat):
return (sum((yhat-y)**2)/len(y))
def mean_absolute_err(y,yhat):
return np.mean((np.abs(y.sub(yhat).mean())/yhat))
def rmse(y,yhat):
return np.sqrt(sum((yhat-y)**2)/len(y))
predictions_ARIMA = np.exp(predictions_ARIMA_log)
plt.plot(train_weekly_resampled_data)
plt.plot(predictions_ARIMA)
plt.title('RMSE: %.4f |MSE: %.4f| MAE: %.4f'% (
rmse(train_weekly_resampled_data, predictions_ARIMA),
mean_sqared_err(train_weekly_resampled_data, predictions_ARIMA),
mean_absolute_err(train_weekly_resampled_data,predictions_ARIMA)))
plt.xlabel('Date')
plt.legend(('Real Values', 'Predicted Values'), loc='lower right')
# forecast
Fcast = predictions_ARIMA.values.predict(start = '11/08/2019', end = '22/09/2019')
Your model is saved in the variable model. You should change your last line to
Fcast = model.predict(start = '11/08/2019', end = '22/09/2019')

How to fix "TypeError: Expected Ptr<cv::UMat> for argument '%s'"

I'm writing codes to accelerate my program using CUDA, but I got a tricky error. I have no idea about it.My environment is OpenCV 4.1.1, python 3.6.
Here is my code.
I define a function to rotate the img,
def rotate(img, angle):
'''
'''
if len(img.shape) == 3:
(rows, cols, channels) = img.shape
out_size = (cols, rows, channels)
else:
(rows, cols) = img.shape
out_size = (cols, rows)
if angle == 0:
dst = img
else:
# img_gpu = cv2.cuda_GpuMat()
img_gpu = cv2.cuda_GpuMat()
out_gpu = cv2.cuda_GpuMat()
# M_gpu = cv2.cuda_GpuMat()
# out_size_gpu = cv2.cuda_GpuMat()
# border_value_gpu = cv2.cuda_GpuMat()
m = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
img_gpu.upload(img)
# M_gpu.upload(M)
# out_size_gpu.upload((12000, 6000))
# border_value_gpu.upload((0, 0, 0))
cols_gpu = cv2.cuda_GpuMat()
rows_gpu = cv2.cuda_GpuMat()
cols_gpu.upload(cols)
rows_gpu.upload(rows)
print(type(img))
print(img.shape)
(row,col) = img.shape
print([img_gpu.size()[0],img_gpu.size()[1]])
# M = np.float32([[1,0,100],[0,1,50]])
# out=cv2.UMat(out_gpu,(284,284))
out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row))
dst = out_gpu.download()
return dst
then I call it.
img = cv2.imread('../FengZhan/temp.png',0)
img_rotate = rotate(img, -10)
it cannot work and has the following error:
<ipython-input-48-41cd06952793> in rotate(img, angle)
36 # M = np.float32([[1,0,100],[0,1,50]])
37 # out=cv2.UMat(out_gpu,(284,284))
---> 38 out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row))
39
40 dst = out_gpu.download()
TypeError: Expected Ptr<cv::UMat> for argument '%s'
I tried to replace img_gpu with cv2.UMat(img_gpu), but it still cannot work.
Anybody help me?
I got this error: TypeError: Expected Ptr<cv::UMat> for argument '%s'
code:
image = cv2.imread("image_path")
image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
Simply because the image path was incorrect and I was loading an image which wasn't there. I realize it might not be your case however I hope it may help others who encounter this error.
I don't understand why do you define in the beginning out_gpu = cv2.cuda_GpuMat(). And in the end you set it again to: out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row)).
The reason why you get this error may be because of your code out_gpu = cv2.cuda.warpAffine(img_gpu, m, (col,row)) argument img_gpu is supposed to be a string link to an image, yet it is defined previously as img_gpu = cv2.cuda_GpuMat(). Try to correct this by replacing the line img_gpu.upload(img) by uploaded_img = img_gpu.upload(img)
Change your image to be numpy array
np.array(image)
It seems to be one bug for OpenCV as I issued at OpenCV cuda bindings for python seem receive wrong param types for cudawarping/src/warp.cpp #2393.
However, even I fix this bug the speed is not satisying (slower than CPU version), if there are some other tricks, maybe we can share with each other.
Good Luck.

Resources