when i tried show 2 image together using opencv - opencv

import cv2
import numpy as np,sys
img1 = cv2.imread('Pictures/orange.jpg')
img2 = cv2.imread('pictures/orange.jpg')
cv2.imshow('apple', img1)
cv2.imshow('orange', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
when i try to run this code.
error Traceback (most recent call last)
in ()
6
7 cv2.imshow('apple', img1)
----> 8 cv2.imshow('orange', img2)
9 cv2.waitKey(0)
10
error: OpenCV(3.4.1) /io/opencv/modules/highgui/src/window.cpp:356: error: (-215) size.width>0 && size.height>0 in function imshow
i am getting this error.

Related

Open CV syntax in google colab

In the following code, I was trying to print the normalized image, which worked well in the google Colab environment. But as soon as I converted that image matrix to a flattened matrix it simply resulted in an error.
import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab.patches import cv2_imshow
%matplotlib inline
import os
vertical = cv2.imread("vertical (1).PNG", cv2.IMREAD_GRAYSCALE)
horizontal = cv2.imread("horizontal (1).PNG", cv2.IMREAD_GRAYSCALE)
vertical = vertical/255
horizontal = horizontal/255
print(vertical)
print(horizontal)
vertical_flattened = vertical.flatten()
horizontal_flattened = horizontal.flatten()
print(vertical_flattened)
print(horizontal_flattened)
plt.rcParams["figure.figsize"]=(20,10)
plt.subplot(2,3,1)
plt.title('Vertical Image')
plt.imshow(vertical, cmap = 'gray')
plt.subplot(2,3,4)
plt.title('Vertical_flattened Image')
plt.imshow(vertical_flattened, cmap = 'gray')
plt.subplot(2,3,2)
plt.title('Horizontal Image')
plt.imshow(horizontal, cmap = 'gray')
cv2.waitKey(0)
The error details are as follows :
TypeError Traceback (most recent call last)
<ipython-input-9-c30222345864> in <module>
25 plt.subplot(2,3,4)
26 plt.title('Vertical_flattened Image')
---> 27 plt.imshow(vertical_flattened, cmap = 'gray')
28
29 plt.subplot(2,3,2)
TypeError: Invalid shape (61746,) for image data
What should I do to print the flattened image? Thanks in advance.

TypeError: Image data of dtype object cannot be converted to float as cv2 is not reading any image but the path is right

I am trying to load an image in Python Jupyter notebook but I am getting an error as it is showing they are not getting any image.
img = cv2.imread(r"C:\Users\DELL\Desktop\download.jpg")
plt.imshow(img)
The output I am getting is :
TypeError Traceback (most recent call last)
<ipython-input-24-639b020df6f2> in <module>()
1 img = cv2.imread(r"C:\Users\DELL\Desktop\download.jpg")
----> 2 plt.imshow(img)
5 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/image.py in set_data(self, A)
692 not np.can_cast(self._A.dtype, float, "same_kind")):
693 raise TypeError("Image data of dtype {} cannot be converted to "
--> 694 "float".format(self._A.dtype))
695
696 if not (self._A.ndim == 2
TypeError: Image data of dtype object cannot be converted to float

Convert numpy ndarray to PIL and and convert it to tensor

def camera(transform):
capture = cv2.VideoCapture(0)
while True:
ret, frame = capture.read()
cv2.imshow('video', frame)
# esc
if cv2.waitKey(1) == 27:
photo = frame
break
capture.release()
cv2.destroyAllWindows()
img = Image.fromarray(cv2.cvtColor(photo, cv2.COLOR_BGR2RGB))
img = img.resize([224, 224], Image.LANCZOS)
if transform is not None:
img = transform(img).unsqueeze(0)
return img
This is my code to get image from the camera,
image_tensor = img.to(device)
And I have an error at the line above...
Traceback (most recent call last):
File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 126, in <module>
main(args)
File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 110, in main
caption = Image_Captioning(args, img)
File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 88, in Image_Captioning
image_tensor = img.to(device)
AttributeError: 'Image' object has no attribute 'to'
The error is like this.
If I have the image as png file and reload it with PIL, it works.
But the one I want is to use the image without saving.
Pls... Someone save me...
You could convert your PIL.Image to torch.Tensor with torchvision.transforms.ToTensor:
if transform is not None:
img = transform(img).unsqueeze(0)
tensor = T.ToTensor()(img)
return tensor
having imported torchvision.transforms as T

I am gettig an error in my program of face recognition. (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

I am using LBPH algorithm for face detection. The part of collecting the data and training is working fine but in the testing part, there is an error
This is code for testing
import cv2
import numpy as np
import webbrowser
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def face_detector(img, size=0.5):
faces = ()
# Convert image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('Printe1r', gray )
if np.count_nonzero(gray) >= 0:
print("in face detector")
faces = face_classifier.detectMultiScale(gray, 1.3, 5)
if faces is ():
return img, []
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2)
roi = img[y:y+h, x:x+w]
roi = cv2.resize(roi, (200, 200))
return img, roi
# Open Webcam
cap = cv2.VideoCapture(0)
print("WebCam opened")
while True:
ret, frame = cap.read()
cv2.imshow('Printe1rwer', frame )
image, face = face_detector(frame)
cv2.imshow('Printe1aas r', image )
print(face)
try:
print("hell1o")
face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
print("hello")
# Pass face to prediction model
# "results" comprises of a tuple containing the label and the confidence value
results = model.predict(face)
print("Helo",results)
if results[1] < 500:
print("in results < 500")
confidence = int( 100 * (1 - (results[1])/400) )
display_string = str(confidence) + '% Confident it is User'
cv2.putText(face, display_string, (100, 120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,120,150), 2)
if confidence > 75:
print("in confidence < 75")
cv2.putText(face, "Hey Vimal", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow('Face Recognition', face )
webbrowser.open('')
break
else:
print("in else")
cv2.putText(face, "Locked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
cv2.imshow('Face Recognition', face )
except Exception as e:
print(e)
cv2.putText(frame, "No Face Found", (220, 120) , cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
cv2.putText(frame, "Locked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
cv2.imshow('Face Recognition', frame )
pass
if cv2.waitKey(1) == 13: #13 is the Enter Key
break
cap.release()
cv2.destroyAllWindows()
The error I am getting is:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-1-3a076399e5b1> in <module>
34 ret, frame = cap.read()
35 cv2.imshow('Printe1rwer', frame )
---> 36 image, face = face_detector(frame)
37 cv2.imshow('Printe1aas r', image )
38 print(face)
<ipython-input-1-3a076399e5b1> in face_detector(img, size)
14 if np.count_nonzero(gray) >= 0:
15 print("in face detector")
---> 16 faces = face_classifier.detectMultiScale(gray, 1.3, 5)
17
18 if faces is ():
error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689:
error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'`
Could somebody help me out??
I am using the OpenCV version 4.2.0
One thing is the value of the variable gray in the face detector function is always a numpy array with all values as zero. I have checked that but it is always zero.
I've tested the first part of your code. It seems to be working, printing gray I get:
TEMP.py:20: SyntaxWarning: "is" with a literal. Did you mean "=="?
if faces is ():
WebCam opened
[[162 162 162 ... 97 97 97]
[161 161 160 ... 95 95 95]
[159 159 161 ... 95 95 95]
...
[252 252 252 ... 164 164 164]
[236 233 229 ... 165 164 164]
[164 158 153 ... 164 164 164]]
Apart from correcting () with == as suggested by the interpreter, I would check:
That the img that comes in face detector is nonzero (just print it, mine is ok).
That you're actually loading the right input source in cap = cv2.VideoCapture(0) (do you have multiple webcams attached?)
Try inserting a if frame: block just after ret, frame = cap.read(). Probably only the first frame is None and it is giving you all the problems.
If the above are ok, the only suspect remains gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)...
A side note: ret, frame = cap.read() reads all the input continuously from the camera, but the pc may be slower than your algorithm in processing every frame. I usually avoid the creation of a long buffer using a trick. After you solve the above, have a look at this.
I tried changing the file path for "haarcascade_frontalface_default.xml" and it worked for me. I mean I provided the exact path for the location.

failure of cvtColor function in opencv

i am just learning image processing but cvtColor function is not working properly. it is showing following error.
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp, line 3737
Traceback (most recent call last):
File "harriscorner.py", line 6, in <module>
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.error: /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
actually i am trying harris corner detection method but cvtColor fucion is not working. help from anyone will be appreciated.
here is my code.
import cv2
import numpy as np
filename = 'chessboard.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv2.imshow('dst',img)
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Since your code is showing error at the very first cvtColor after reading from a file, it is possible that the imread operation was not successful.
Start by ensuring that your image is correctly read:
filename = 'chessboard.jpg'
img = cv2.imread(filename)
cv2.imshow("src",img)
cv2.waitKey(0)#proceed to remaining code when you press a key
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
If you're not able to see you image in this imshow, then check if the filePath is correct.
Try this:
filename = './chessboard.jpg'

Resources