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
Related
I used Zbar and OpenCV to read the QR code in the image below but both failed to detect it. For ZBar, I use pyzbar library as the python wrapper. There are images that QR is detected correctly and images really similar to the successful ones that fail. My phone camera can read the QR code in the uploaded image which means it is a valid one. Below is the code snippet:
from pyzbar.pyzbar import decode
from pyzbar.pyzbar import ZBarSymbol
import cv2
# zbar
results = decode(cv2.imread(image_path), symbols=[ZBarSymbol.QRCODE])
print(results)
# opencv
qr_decoder = cv2.QRCodeDetector()
data, bbox, rectified_image = qr_decoder.detectAndDecode(cv2.imread(image_path))
print(data, bbox)
What type of pre-processing will help to increase the rate of success for detecting QR codes?
zbar, which does some preprocessing, does not detect the QR code, which you can test running zbarimg image.jpg.
Good binarization is useful here. I got this to work using the kraken.binarization.nlbin() function of the Kraken library. The library is for OCR, but works very well for QR codes, too, by using non-linear processing. The Kraken binarization code is here.
Here is the code for the sample:
from kraken import binarization
from PIL import Image
from pyzbar.pyzbar import decode
from pyzbar.pyzbar import ZBarSymbol
image_path = "image.jpg"
# binarization using kraken
im = Image.open(image_path)
bw_im = binarization.nlbin(im)
# zbar
decode(bw_im, symbols=[ZBarSymbol.QRCODE])
[Decoded(data=b'DE-AAA002065', type='QRCODE', rect=Rect(left=1429, top=361, width=300, height=306), polygon=[Point(x=1429, y=361), Point(x=1429, y=667), Point(x=1729, y=667), Point(x=1723, y=365)])]
The following picture shows the clear image of the QR code after binarization:
I had a similar issue, and Seanpue's answer got me on the right track for this problem. Since I was already using the OpenCV library for image processing rather than PIL, I used it to perform Otsu's Binarization using the directions in an OpenCV tutorial on Image Thresholding. Here's my code:
import cv2
from pyzbar.pyzbar import decode
from pyzbar.pyzbar import ZBarSymbol
image_path = "qr.jpg"
# preprocessing using opencv
im = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(im, (5, 5), 0)
ret, bw_im = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# zbar
decode(bw_im, symbols=[ZBarSymbol.QRCODE])
[Decoded(data=b'DE-AAA002065', type='QRCODE', rect=Rect(left=1429, top=362, width=300, height=305), polygon=[Point(x=1429, y=362), Point(x=1430, y=667), Point(x=1729, y=667), Point(x=1724, y=366)])]
Applying the gaussian blur is supposed to remove noise from the picture to make the binarization more effective, but for my application it didn't actually make much difference. What was vital was to convert the image to grayscale to make the threshold function work (done here by opening the file with the cv2.IMREAD_GRAYSCALE flag).
QReader use to work quite well for these cases.
from qreader import QReader
import cv2
if __name__ == '__main__':
# Initialize QReader
detector = QReader()
img = cv2.cvtColor(cv2.imread('92iKG.jpg'), cv2.COLOR_BGR2RGB)
# Detect and Decode the QR
print(detector.detect_and_decode(image=img))
This code output for this QR:
DE-AAA002065
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 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.
I am trying to read and display an image in Python OpenCV.
Executing the following code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('dumb.jpg', cv2.IMREAD_GRAYSCALE)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Results in the following error:
cv2.error:
C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\highgui\src\window.cpp:325: error: (-215) size.width>0 && size.height>0 in function cv::imshow
How to solve this?
NOTE: I have all the prerequisites needed to execute this (python 2.7, opencv 3.3
matplotlib, numpy)
If you are trying to display OpenCV image using matplotlib, use the code below.
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline # if you are running this code in Jupyter notebook
# reads image 'opencv-logo.png' as grayscale
img = cv2.imread('/path_to_image/opencv-logo.png', 0)
plt.imshow(img, cmap='gray')
there is a tutorial on http://docs.opencv.org/3.1.0/dc/d2e/tutorial_py_image_display.html
import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('/path_to_image/messi5.jpg',0)
# show image
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
use an absolute path to the image then you have no path problems
https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths
OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow
I have written a short post to learn image reading with OpenCV in Python. You can see the below code snippet with the description.
import cv2 #Import openCV
import sys #import Sys. Sys will be used for reading from the command line. We give Image name parameter with extension when we will run python script
#Read the image. The first Command line argument is the image
image = cv2.imread(sys.argv[1]) #The function to read from an image into OpenCv is imread()
#imshow() is the function that displays the image on the screen.
#The first value is the title of the window, the second is the image file we have previously read.
cv2.imshow("OpenCV Image Reading", image)
cv2.waitKey(0) #is required so that the image doesn’t close immediately. It will Wait for a key press before closing the image.
To read an image with OpenCV you have to use the following synthax. If it doesn't work, there is a problem with the installation.
import cv2
image = cv2.imread('path_of_the_image.png')
cv2.imshow('img', image)
cv2.waitKey(0)
You didn't post the error it gives..
EDIT: I don't understand the negative points...for what ??
The reason for this error message is that cv2.imread() was unable to find the image where it was looking for the image. This should work if you add the full path to the image, like
img = cv2.imread('/home/foo/images/dumb.jpg',cv2.IMREAD_GRAYSCALE)
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# Hide grid lines
fig, ax = plt.subplots(figsize=(10,10))
ax.grid(False)
im=cv2.imread('./my_images.jpg')
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
plt.show()
It use cv2.COLOR_BGR2RGB because it convert default settings of OpenCV which using BGR to RGB format
Use 0 rather than cv2.IMREAD_GRAYSCALE and I would hard code the location of the file rather than refer to it like that for example if it was on the C drive put 'C:\\Filename.jpg'
Try this one :
import cv2 as cv #openCV-3.4.1
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('image path and name .file type ',0)
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
It looks like your code is fine. The problem seems to be in the dimension of image that is being provided in the parameters. The error code says: size > 0 && width > 0. This condition is not meeting properly. Either dimension size or width is less than zero. You may want to check any other image and try with that.
I try to use SimpleCV example's code(http://www.simplecv.org/), which shows the SimpleCV threshold function, the threshold method sets each pixel in an image to black or white depending on its brightness.
But it doesn't work
Error like this:
ERROR:
Traceback (most recent call last):
File "Camera_1.py", line 37, in <module>
img = Image('http://i.imgur.com/lfAeZ4n.png')
File "c:\Python27\lib\site-packages\SimpleCV\ImageClass.py", line 686, in __in
it__
`source = pil.open(im).convert("RGB")`
NameError: global name 'pil' is not defined
Code like this:
from SimpleCV import Image, Color, Display
# Make a function that does a half and half image.
def halfsies(left,right):
result = left
# crop the right image to be just the right side.
crop = right.crop(right.width/2.0,0,right.width/2.0,right.height)
# now paste the crop on the left image.
result = result.blit(crop,(left.width/2,0))
# return the results.
return result
# Load an image from imgur.
img = Image('http://i.imgur.com/lfAeZ4n.png')
# binarize the image using a threshold of 90
# and invert the results.
output = img.binarize(90).invert()
# create the side by side image.
result = halfsies(img,output)
# show the resulting image.
result.show()
# save the results to a file.
result.save('juniperbinary.png')
Code in here
You need to install the Python Imaging Library (PIL), which is a 3rd party module. I think SimpleCV is supposed to install PIL as part of the overall installation process, but PIL is one of those weirder programs to set up.
Try typing in the following from the command line:
pip install pil
Alternatively, you can install using the binary.
If that still doesn't work, try installing pillow, which is a friendlier and actively-developed fork of PIL:
pip install pillow