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
Related
Following this https://www.youtube.com/watch?v=I8tHLZDDHr4&list=WL&index=1&ab_channel=Pysource tutorial on YouTube for my own project, answers I found basically had the exact same code, but my code gives me this error:
Traceback (most recent call last): File "c:\Users\NoName69\Desktop\ProJects\PyJects\Homography\test.py", line 31, in <module> matrix, mask = cv2.findHomography(query_p, train_p, cv2.RANSAC, 5.0) cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build 5rb_9df3\opencv\modules\calib3d\src\fundam.cpp:385: error: (-28:Unknown error code -28) The input arrays should have at least 4 corresponding point sets to calculate Homography in function "cv::findHomography"
Code:
from cv2 import cv2
import numpy as np
img1 = cv2.cvtColor(cv2.imread("Aim Circle.png"), cv2.COLOR_RGB2GRAY)
img2 = cv2.cvtColor(cv2.imread("Map.png"), cv2.COLOR_RGB2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp_img1, desc_img1 = sift.detectAndCompute(img1, None)
kp_img2, desc_img2 = sift.detectAndCompute(img2, None)
img1 = cv2.drawKeypoints(img1, kp_img1, img1)
img2 = cv2.drawKeypoints(img2, kp_img2, img2)
index_params = dict(algorithm = 0, trees = 5)
search_params = dict()
flann = cv2.FlannBasedMatcher(index_params, search_params)
while True:
matches = flann.knnMatch(desc_img1, desc_img2, k = 2)
good_kp = []
for m, n in matches:
if m.distance < 0.75 * n.distance:
good_kp.append(m)
if len(good_kp) > 2:
query_p = np.float32([kp_img1[m.queryIdx].pt for m in good_kp]).reshape(-1, 1 ,2)
train_p = np.float32([kp_img2[m.trainIdx].pt for m in good_kp]).reshape(-1, 1, 2)
matrix, mask = cv2.findHomography(query_p, train_p, cv2.RANSAC, 5.0)
if cv2.waitKey(25) & 0xFF == ord(" "):
cv2.destroyAllWindows()
break
OpenCv also gives this warning:
[ WARN:0] global c:\users\appveyor\appdata\local\temp\1\pip-req-build-5rb_9df3\opencv_contrib\modules\xfeatures2d\misc\python\shadow_sift.hpp (15) cv::xfeatures2d::SIFT_create DEPRECATED: cv.xfeatures2d.SIFT_create() is deprecated due SIFT tranfer to the main repository. https://github.com/opencv/opencv/issues/16736
I have found out the problem. OpenCV cannot find enough features in the file "Aim Circle.png", and so gives this error. If anyone knows another way to find a picture that is similar embedded in another picture it would be greatly appreciated.
i think in
if len(good_kp) > 2:
you have to substiture the value of 2 with a value greater than 4:
example: if len(good_kp) > 10:
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()
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
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)
i started on a project which inputs 2 images and detect the keypoints using sift and then checking the similarity of the 2 images
i actually completed the project without converting the image files to greycode but later i understood that converting images to grey code and then comparing gives more accurate results
so i wrote the code to convert the image to greycode
but i am facing a problem
import cv2
import easygui
import sys
from matplotlib import pyplot as plt
print "image 1 :",sys.argv[1]
print "image 2 :",sys.argv[2]
print "******** comparing images please wait *********"
file1=sys.argv[1]
file2=sys.argv[2]
img1 = cv2.imread(file1,0)#queryImage
img2 = cv2.imread(file2,0)#trainImage
gray_image1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray_image2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
i am getting an error
image 1 : taj1.jpg
image 2 : taj2.jpg
******** comparing images please wait *********
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /root/opencv-3.3.0/opencv-3.3.0/modules/imgproc/src/color.cpp, line 10638
Traceback (most recent call last):
File "image_similarity.py", line 14, in <module>
gray_image1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
cv2.error: /root/opencv-3.3.0/opencv-3.3.0/modules/imgproc/src/color.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cvtColor
how can i resolve it
thanks in advance
You don't need to convert it, if you load it as you do.
img1 = cv2.imread(file1,0)#queryImage
img2 = cv2.imread(file2,0)#trainImage
Second parameter=0 means you load it as gray scale image.