I am trying to detect humans in images using the haarcascade full body algorithm using OpenCv in Python.
when i consider using it on a single image, I face no issues.
import numpy as np
import cv2 as cv
body_cascade = cv.CascadeClassifier(r'...\haarcascade_fullbody.xml')
image = cv.imread(r'...\image.jpg')
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
body = body_cascade.detectMultiScale(gray, 1.01, 4)
for (x,y,w,h) in body:
cv.rectangle(image,(x,y),(x+w,y+h),(255,0,0),3)
But, when I try to use the same program and iterate over several images at once, I get a cryptic OpenCv error. I have some images in a folder and I want to separate images with humans in them from those that don't. I wrote the following:
import os
for file in os.walk(r'...\Folder'):
file=str(file)
im=cv.imread(file)
gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
body = body_cascade.detectMultiScale(gray, 1.01, 4)
for (x,y,w,h) in body:
cv.rectangle(im,(x,y),(x+w,y+h),(255,0,0),3)
if(body.size >= 0):
print('okay')
else:
print('Not okay')
But I get the following error :
error: OpenCV(3.4.2) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'cv::CvtHelper<struct cv::Set<3,4,-1>,struct cv::Set<1,-1,-1>,struct cv::Set<0,2,5>,2>::CvtHelper'
for the line gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
I am unable to understand what the error is and why the same code that works when taking individual images is working but not the case when iterating through a folder. Do I need to resize the images ?
Also, I tried with keeping just one image in the folder, on which the code had worked before, still doesn't work.
Doc, it seems like OpenCV fails to locate the image. What happens if you're using full paths instead of relative ones? (and what are the three dots there "..." ?)
please dump the file that you read back to disc for debugging purposes and I think you'll be surprised.
Related
I am trying to apply laplacian to a median filter output to get a sharper image, by later processing. The code snippet is as below :
img = plt.imread('example.png')
img_res = cv.resize(img,(256,256))
gray_image = cv.cvtColor(img_res, cv.COLOR_BGR2GRAY)
median_img = median_filter(gray_image, 5)
# Calculate the Laplacian
lap_img = cv.Laplacian(median_img,cv.CV_64F)
The input image is a RGB medical image. I am faced with the following error, when running this code:
cv2.error: OpenCV(4.1.2) C:/projects/opencv-python/opencv/modules/imgproc/src/filter.simd.hpp:3175: error: (-213:The function/feature is not implemented) Unsupported combination of source format (=5), and destination format (=6) in function 'cv::opt_AVX2::getLinearFilter'
This error occurs for any image from the dataset. Could you please point out what could be the issue? The example is followed from this link for grayscale images.
Instead of using two different libraries (matplotlib and opencv), stick to using one library at a time while performing image-processing. The reason is because these two libraries use different formats to store images. matplotlib uses RGB convention while opencv uses BGR. My guess is that you're encountering this error due to using matplotlib to load the image, and then performing operations with opencv. Simply, loading the image using cv2.imread() instead of plt.imread() seems to fix the problem
Input -> Output
import cv2
from scipy.ndimage.filters import median_filter
import numpy as np
img = cv2.imread('1.png')
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
median_img = median_filter(gray_image, 5)
# Calculate the Laplacian
lap_img = cv2.Laplacian(median_img,cv2.CV_64F).astype(np.uint8)
cv2.imshow('lap_img', lap_img)
cv2.imwrite('lap_img.png', lap_img)
cv2.waitKey()
I am new to computer vision and image processing and am using this code
from skimage.feature import hog
hog_list, hog_img = hog(test_img_gray,
orientations=8,
pixels_per_cell=(16, 16), cells_per_block=(1, 1),
block_norm='L1',
visualise=True,
feature_vector=True)
plt.figure(figsize=(15,10))
plt.imshow(hog_img)
to get this HOG visualization image
I have 2 questions at this point:
When I try to save this image (as a .pdf or .jpg) the resulting image is pure black. Converting this image to PIL format and examining it with
hog_img_pil = Image.fromarray(hog_img)
hog_img_pil.show()
still shows the image as pure black. Why is this happening and how can I fix it?
When I try to run this code
hog_img = cv2.cvtColor(hog_img, cv2.COLOR_BGR2GRAY)
to convert the image to grayscale I get the error error: (-215) depth == CV_8U || depth == CV_16U || depth == CV_32F in function cvtColor. What do I need to do to get this image in grayscale and why would this be happening?
As additional information, running hog_img.shape returns (1632, 1224) which is just the size of the image, which I had initially interpreted to mean that the image is already is already in grayscale (since it appears to be lacking a dimension for color channel). However, when I then tried to run
test_img_bw = cv2.adaptiveThreshold(
src=hog_img,
maxValue=255,
adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
thresholdType=cv2.THRESH_BINARY,
blockSize=115, C=4)
I got the error error: (-215) src.type() == CV_8UC1 in function adaptiveThreshold which this answer seems to indicate means that the image is not in grayscale.
Finally, another bit of useful information is that running print(hog_img.dtype) on the image returns float64.
I will continue to debug, in the meantime
Thanks for any thoughts :)
Inverting the image with hog_img_inv = cv2.bitwise_not(hog_img) and using
plt.figure(figsize=(15,10))
plt.imshow(hog_img_uint8_inv)
showed that the lines were in fact there but are very faint (I've included the image here for comletness, but you can barley see it (but trust me, it's there)). I will have to do some more processing of the image to get the lines more distinguishable.
Running print(hog_img.dtype) showed that the dtype was float64 when (I think) it should have been uint8. I fixed this by running hog_img_uint8 = hog_img.astype(np.uint8) which seems to have fixed the problem with passing the image to other algorithms (eg. cv2.adaptiveThreshold).
If had the same problem. But if you look inside the docu, they also use this code for better visualisation:
# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))
But I still have the same problem. Visualisation with matplotlib is no problem. saving the image with opencv (or skimage) saves only a black image...
So working with windows, python 2.7 and simplecv I am making a live video with my webcam and want simplecv to give me a grayscale version of the video. Is there any simple way to achieve that?
I found the command
grayscale()
on the opencv page, which should do exactly that but when I run it I get the error:
NameError: name "grayscale" is not defined
I am currently using this prewritten code for object tracking but I don't know whether I should use the command I found, and where in the code I should put it, does anybody have an idea? :
print __doc__
import SimpleCV
display = SimpleCV.Display()
cam = SimpleCV.Camera()
normaldisplay = True
while display.isNotDone():
if display.mouseRight:
normaldisplay = not(normaldisplay)
print "Display Mode:", "Normal" if normaldisplay else "Segmented"
img = cam.getImage().flipHorizontal()
dist = img.colorDistance(SimpleCV.Color.BLACK).dilate(2)
segmented = dist.stretch(200,255)
blobs = segmented.findBlobs()
if blobs:
circles = blobs.filter([b.isCircle(0.2) for b in blobs])
if circles:
img.drawCircle((circles[-1].x, circles[-1].y), circles[-1].radius(),SimpleCV.Color.BLUE,3)
if normaldisplay:
img.show()
else:
segmented.show()
There are multiple ways to do this in SimpleCV.
One way has been already described, it's the toGray() method.
There's also a way you can do this with gaussian blur, which also helps to remove image noise:
from SimpleCV import *
img = Image("simplecv")
img.applyGaussianFilter(grayscale=True)
After the third line, img object contains the image with a lot less high-frequency noise, and converted to grayscale.
You may check out pyimagesearch.com who works with OpenCV, but he explains why applying Gaussian Blur is a good idea.
In simple cv theres a function called toGray() for example:
import SimpleCV as sv
img = img.jpg
sv.img.jpg.toGray()
return gimg.jpg
i am using opencv2 and python on raspberry pi. and i am new with python and opencv. i tried to read a jpeg image and display image it shows the following error:
/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: \
error: (-215) size.width>0 && size.height>0 in function imshow.
and the code is:
import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()
The image fails to load (probably because you forgot the leading / in the path). imread then returns None. Passing None to imshow causes it to try to create a window of size 0x0, which fails.
The poor error handling in cv probably owes to its quite thin wrapper layer on the C++ implementation (where returning NULL on error is a common practice).
it's the path which is causing the problem, i had the same problem but when i gave the full path of the image it was working perfectly.
While using Raspbian in Rpi 3 I had the same problem when trying to read qrcodes. The error is because cv2 was not able to read the image. If using png image install pypng module.
sudo pip install pypng
Use r in the code where you specified the file address.
For Example:
import cv2
img = cv2.imread(r'D:\Study\Git\OpenCV\resources\lena.png')
cv2.imshow('output', img)
cv2.waitKey(0)
r stands for "raw" and will cause backslashes in the string to be interpreted as actual backslashes rather than special characters.
In my case, I had forgotten to change the working directory of my terminal to that of my code+testImage. Hence, it failed to find the image there.
Finally, this is what worked for me:
I saved the image and Python file on Desktop. I changed my cmd directory to it,
cd Desktop
And then checked for my file:
ls
And this was my code that worked:
import cv2
import numpy as np
im = cv2.imread('unnamed.jpg')
#Display the image
cv2.imshow('im',im)
cv2.waitKey(2000) #Milliseconds
I am also getting a similar error, so instead of opening a new question, I thought maybe it would be a good idea to gather it all here since there's already some helpful answers...
My code (textbook code to open a video using OpenCV in Python):
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
os.chdir(path)
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file)
if not cap.isOpened():
print("Error opening Video File.")
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
The reason why I am dumbfounded is that I am getting the same error - BUT - the video is actually played... When running the code the Python interpreter opens up an instance of Python running the video. Once the video ends, it breaks out of the loop, closes the video and throws the error:
Traceback (most recent call last):
File "C:/Users/username/Documents/smile-main/video-testing.py", line 24, in
cv.imshow('frame',frame)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wwma2wne\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
I'd appreciate any input!
**
EDIT: How I fixed my error!
**
I encased my code in a try/except like this:
# Import required libraries
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
# test_path = 'C:/Users/username/Downloads'
os.chdir(path)
os.getcwd()
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file) #cap for "Video Capture Object"
if not cap.isOpened():
print("Error opening Video File.")
try:
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
except:
print("Video has ended.")
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
I'd still appreciate any input on why this error popped up even though the video played fine, and why the try/except eliminated it.
Thank you!
One of the reasons, this error is caused is when there is no file at the path specified. So, a good practice will be to verify the path like this ( If you are on a linux based machine ):
ls <path-provided-in-imread-function>
You will get an error if the path is incorrect or the file is missing.
While reading the image file, specifying the color option should solve this,
for example:
image=cv2.imread('img.jpg',cv2.IMREAD_COLOR)
adding the cv2.IMREAD_COLOR should solve this
This problem happened to me when i just failed to write the extension of the image.
Please check if you forgot to write the extension or any other part of the full path to the image.
Remember, extension is required whether you are printing image using OpenCV or Mathplotlib.
I solve it by using this code
os.chdir(f"{folder_path}")
It is because the image is not loaded. For me at VScode the relative path was problem but after copying the file path from VSCode itself the problem was solved.
I had the same problem too, on VSCode. Tried running the same code on Notepad++ and it worked. To fix this issue on VSCode, don't forget to open the folder that you're working in on the left pane. This solved my issue.
I try to find contours in a binary image but when try to execute cvFindContours it gives me that error message
Traceback (most recent call last): File "convert.py", line 30, in
contour = cvFindContours(img2, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) File
"/usr/lib/pymodules/python2.7/opencv/cv.py", line 580, in
cvFindContours
count, seq = cvFindContoursUntyped( *args ) File "/usr/lib/pymodules/python2.7/opencv/cv.py", line 6521, in
cvFindContoursUntyped
return _cv.cvFindContoursUntyped(*args) RuntimeError: openCV Error:
Status=Incorrect size of input array
function name=cvStartFindContours
error message=
file_name=/build/buildd/opencv-2.1.0/src/cv/cvcontours.cpp
line=205
I using fresh installed Ubuntu 11.10 and Opencv 2.3.1.
Here is my source code
from opencv.cv import *
from opencv.highgui import *
image = cvLoadImage('test.png')
def getthresholdedimg(image):
size = cvSize(640, 480)
imghsv=cvCreateImage(cvGetSize(image),8,3)
cvCvtColor(image,imghsv,cv.CV_BGR2HSV)
imgblue=cvCreateImage(cvGetSize(image),8,1)
imgblue2=cvCreateImage(cvGetSize(image),8,1)
imgthreshold=cvCreateImage(cvGetSize(image),8,1)
cvInRangeS(imghsv,cvScalar(100,100,100),cvScalar(120,255,255),imgblue)
cvInRangeS(imghsv,cvScalar(100,100,100),cvScalar(120,255,255),imgblue2)
cvAdd(imgblue,imgblue,imgthreshold)
return imgthreshold
cvFlip(image,image,1)
cvSmooth(image, image, CV_GAUSSIAN, 3, 0)
imgthresh=getthresholdedimg(image)
cvErode(imgthresh,imgthresh,None,3)
cvDilate(imgthresh,imgthresh,None,10)
storage = cvCreateMemStorage(0)
img2=cvCloneImage(imgthresh)
contour = cvFindContours(img2, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
my original and binary image
Original image
http://tinypic.com/r/34rul9x/6
and blue filtered binary image
http://tinypic.com/r/ifbotx/6
Find contours in python cv2
import numpy as np
import cv2
img = cv2.imread('sample_image.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 3)
cv2.imshow('img',img)
cv2.waitKey(0)
I think this style of API is discontinued from OpenCV. Presently two API is there, old one is cv obtained by
>>> import cv2.cv as cv
And the second and new one is the cv2 available as :
>>> import cv2
Regarding the error :
Replace import statement with from cv2.cv import *
Then remove all the cv prefix, it should work fine.
NOTE :
I think you are trying for color tracking of objects.
But since you have OpenCV 2.3.1, why do you use very old Python API ?
New Python API is cv2 version, which is simple, fast and flexible. Also, it is difficult to play with various objects in Old API compared to new API. So I would recommend you to update to new cv2 API. It is even difficult debug errors in old API.
You can find color tracking code with new cv2 API in this link : http://goo.gl/db2KW
Or if you are sure to use old API, here is the code : http://goo.gl/AFEmv