How to use orb on a image in CV2? - python

I wish to use ORB (http://docs.opencv.org/3.1.0/d1/d89/tutorial_py_orb.html#gsc.tab=0) on a 28*28 grayscale image (handwritten digits), where each pixel has a number from 0 to 255.
This is the code I used:
# image = {load the array of 754 numbers}
orb = cv2.ORB_create()
image = image.reshape(28, 28))
kp = orb.detect(image, None)
But I keep getting this error:
OpenCV Error: Assertion failed (depth == CV_8U || depth == CV_16U || depth == CV_32F) in cvtColor, file /home/yahya/Documents/_other_downloaded_apps/opencv/modules/imgproc/src/color.cpp, line 7935
Traceback (most recent call last):
File "/home/yahya/Documents/hello.py", line 118, in <module>
kp = orb.detect(image, None)
cv2.error: /home/yahya/Documents/_other_downloaded_apps/opencv/modules/imgproc/src/color.cpp:7935: error: (-215) depth == CV_8U || depth == CV_16U || depth == CV_32F in function cvtColor
How can I do this and why am I getting this error?
UPDATE
I seemed to have solved part of this problem. It turns out that orb accepts float32 numbers (not 64).
Therefore I updated my code as follows:
orb = cv2.ORB_create()
image = feature_x[0].reshape(28, 28).astype('float32')
kp = orb.detect(image, None)
But now I have the following error:
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in ipp_cvtColor, file /home/yahya/Documents/_other_downloaded_apps/opencv/modules/imgproc/src/color.cpp, line 7456
Traceback (most recent call last):
File "/home/yahya/Documents/hello.py", line 188, in <module>
kp = orb.detect(image, None)
cv2.error: /home/yahya/Documents/_other_downloaded_apps/opencv/modules/imgproc/src/color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function ipp_cvtColor

The image you are trying to load isn't compatible type for the orb. You should convert it first before using it. Also you don't need reshape if you are loading it into numpy array
orb = cv2.ORB_create()
image = image.astype(np.uint8, copy=False)
kp = orb.detect(image, None)

Related

How to convert python np.array to cv2 image

Following code:
img = np.array([[[1,2,4]]])
cv2.subtract(img, tuple([1.0]))
Results in error:
Traceback (most recent call last): File "", line 1, in
cv2.error: OpenCV(4.4.0)
C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-nxx381if\opencv\modules\core\src\arithm.cpp:671:
error: (-215:Assertion failed) type2 == CV_64F && (sz2.height == 1 ||
sz2.height == 4) in function 'cv::arithm_op'
If I change the img to:
img = np.array([[[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4]]])
Then it works correctly
In my case I have images of different sizes mono and color and I want to subtract constant value with saturation. The Shapes are HxWx1 or HxWx3 (different datatypes)
How to correctly use cv2.subtract for such cases ?
Edit:
I would like to keep high performance and avoid to allocate temporary arrays / types conversions
You can just subtract a constant value from a numpy array:
img = np.array([[[1,2,4],[1,2,4],[1,2,4],[1,2,4],[1,2,4]]])
img_new=img-1
or if you want to use cv2.substract:
constant = 3
img_new_2=cv2.subtract(img, constant*np.ones(img.shape).astype(type(img[0,0,0])))
edit:
if you want to show this image using opencv you have to convert it to a valid type.
cv2.imshow("window", img_new_2.astype(np.int8))
cv2.waitKey(0)
cv2.destroyAllWindows()

Convert numpy array of 3*n*n images to 1*n*n?

I have 800 images stored in numpy array of size (800, 3,256, 256), which I want to convert to (800, 1,256, 256).
I tried using cv2 library to achieve this but I am getting an error. What the easiest way to implement this?
train_img[i]= cv2.cvtColor(train_img[i], cv2.COLOR_BGR2RGB)
train_img[i]= cv2.cvtColor(train_img[i], cv2.COLOR_BGR2GRAY)
Traceback (most recent call last):
File "<ipython-input-82-e993ce67611f>", line 3, in <module>
train_img[i]= cv2.cvtColor(train_img[i], cv2.COLOR_BGR2RGB)
error: C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp:11010: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cv::cvtColor
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11016
OpenCV Error: Bad number of channels (Source image must have 1, 3 or 4 channels) in cvConvertImage, file C:\ci\opencv_1512688052760\work\modules\imgcodecs\src\utils.cpp, line 622
OpenCV Error: Bad number of channels (Source image must have 1, 3 or 4 channels) in cvConvertImage, file C:\ci\opencv_1512688052760\work\modules\imgcodecs\src\utils.cpp, line 622
OpenCV Error: Bad number of channels (Source image must have 1, 3 or 4 channels) in cvConvertImage, file C:\ci\opencv_1512688052760\work\modules\imgcodecs\src\utils.cpp, line 622
OpenCV Error: Bad number of channels (Source image must have 1, 3 or 4 channels) in cvConvertImage, file C:\ci\opencv_1512688052760\work\modules\imgcodecs\src\utils.cpp, line 622
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
2020-11-19 05:55:59.003947: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
2020-11-19 05:56:13.086709: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2020-11-19 05:56:13.088369: E tensorflow/stream_executor/cuda/cuda_driver.cc:351] failed call to cuInit: UNKNOWN ERROR (303)
2020-11-19 05:56:13.108395: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-FAJP7DN
2020-11-19 05:56:13.109348: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-FAJP7DN
2020-11-19 05:56:13.125396: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
OpenCV Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file C:\ci\opencv_1512688052760\work\modules\imgproc\src\color.cpp, line 11010
As pointed by Elyas Karimi cv2.cvtColor expects the input images to be 256x256x3 and not 3x256x256. You can transpose the images back and forth.
However, since converting from RGB to gray is a rather simple operation:
0.2989 * R + 0.5870 * G + 0.1140 * B
You can explicitly and efficiently do the conversion:
# assuming your input is in BGR order
train_img = 0.289 * train_img[:, 2, ...] + 0.587 * train_img[:, 1, ...] + 0.114 * train_img[:, 0, ...]
In many cases the exact weight of each channel is not too critical, and a simple mean over channels can do just fine:
train_img = train_img.mean(axis=1)
Correct me if i am wrong, you have images of 256*256 and they have 3 channels making it 256*256*3
Now you want to make them one channeled as 256*26*1.
By losing channel information, you are converting RGB/BGR image into grey scale. Now to do that with OpenCV you will need to make them 256*256*3, it wont work on 3*256*256
So to do that lets take
from numpy import moveaxis
#image[i].shape=3*256*256
data = moveaxis(image[i], 2, 0)
#data.shape=256*256*3
Now pass this into OpenCv cvt.color
data= cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
data= cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
OR Use this
data = 0.289 * data[:, 2, ...] + 0.587 * data[:, 1, ...] + 0.114 * data[:, 0, ...]

OpenCV resize error(-215:Assertion Failed)

This is my code for building a linear classifier for images and cv2.resize() is throwing error while converting the image from original size to (32,32)
import numpy as np
import cv2
labels = ["dog","cat","panda"]
np.random.seed(1)
W = np.random.randn(3,3072)
b = np.random.randn(3)
orig = cv2.imread("panda_00001.png")
image = cv2.resize(orig,(32,32)).flatten()
scores = W.dot(image) + b
for (label,score) in zip(labels,scores):
print("[INFO] {}:{:.2f}".format(label,score))
cv2.putText(orig,"Label:{}".format(labels[np.argmax(scores)]),(10,30),cv2.FONT_HERSHEY_SIMPLEX,0.9,(0,255,0),2)
cv2.imshow("Image",orig)
cv2.waitkey(0)
Getting this error on execution
Traceback (most recent call last):
File "linearclassifier.py", line 11, in <module>
image = cv2.resize(orig,(32,32)).flatten()
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:3929: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
Your picture path seems to be wrong or invalid.
It's always good practice to integrate a null check to the read picture in your script:
eg:
import cv2
...
img = cv2.imread("myImage.jpg")
if (img.size == 0):
# error handling or throw exception here!
# do stuff with image here

How can I take inverse Fourier transform of an image twice?

I want to apply the inverse discrete Fourier transform on the image twice. For this I did the following:
img = cv2.imread("a.png", 0)
img_back = cv2.idft(cv2.idft(img))
cv2.imwrite("f.png", img_back)
But I get an error saying:
Traceback (most recent call last):
File "test2.py", line 26, in <module>
img_back = cv2.idft(cv2.idft(img))
cv2.error: OpenCV(4.0.0) /Users/travis/build/skvark/opencv-python/opencv/modules/core/src/dxt.cpp:3335: error: (-215:Assertion failed) type == CV_32FC1 || type == CV_32FC2 || type == CV_64FC1 || type == CV_64FC2 in function 'dft'
I cannot understand the reason for this. How could I take the inverse fourier transform of the image twice?
The error message tells you that the input to the idft function must be 32-bit or 64-bit float, with one or two channels (complex data is represented as two channels).
This error happens because img is an integer type (as expected because you read it in from a PNG file). To correct it, convert it to a floating-point type:
img = cv2.imread("a.png", 0)
img = img.astype('f')
img_back = cv2.idft(cv2.idft(img))

compare Image similarity using HOG

Using python we need to find similarities between any type of image.
In the below code snippet, we are reading all images from the folder and extracting the histograms from them and storing the histograms in hashtable for comparision.
for imagePath in paths.list_images(imagesfolderpath):
image = cv2.imread(imagePath)
if image is None or len(image)<=112:
print()
else:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
winStride = (8,8)
padding = (8,8)
locations = ((10,20),)
hist = hog.compute(image,winStride,padding,locations)
labels.append(imagePath.split("/")[-2])
if len(hist)>0:
data.append(hist)
hashtable[imagePath] = hist
below code snippet is used for histogram comparision
for key, value in hashtable.iteritems():
count+=1
mydir = os.path.join(outpath, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f'))
os.makedirs(mydir)
for key1, value1 in hashtable.iteritems():
score = cv2.compareHist(np.array(value, dtype=np.int8),np.array(value1, dtype=np.int8), cv2.HISTCMP_BHATTACHARYYA)
While histogram comparision the error encountered is as follows:
OpenCV Error: Assertion failed (H1.type() == H2.type() && H1.depth() == CV_32F) in compareHist, file /home/administrator/Desktop/vijay/openface/opencv-3.0.0/modules/imgproc/src/histogram.cpp, line 2281
Traceback (most recent call last):
File "TestHOG.py", line 118, in <module>
score = cv2.compareHist(np.array(value, dtype=np.int8),np.array(value1, dtype=np.int8), cv2.HISTCMP_BHATTACHARYYA)
cv2.error: /home/administrator/Desktop/vijay/openface/opencv-3.0.0/modules/imgproc/src/histogram.cpp:2281: error: (-215) H1.type() == H2.type() && H1.depth() == CV_32F in function compareHist

Categories