abidrahmank / opencv2-python-tutorials Goto Github PK
View Code? Open in Web Editor NEWThis repo contains tutorials on OpenCV-Python library using new cv2 interface
This repo contains tutorials on OpenCV-Python library using new cv2 interface
A minor problem in source/py_tutorials/py_imgproc/py_pyramids/py_pyramids.rst
The laplacians are being generated with
L = cv2.subtract(gpA[i-1],GE)
... however the datatype is 'uint8' so results which should be negative are being clipped to zero. As a result the reconstruction fails: this is clear by comparing the left and right parts of the result (away from the transition) to the original images - they should be the same as the original, but are brighter and less sharp (as if a haze has been added) due to loss of the negative Laplacian terms.
It can fixed by working in int16:
# generate Gaussian pyramid for A
G = A.astype('int16')
...
G = B.astype('int16')
( instead of A.copy().. )
... which gives the proper result.
It's also possible to improve the the illustration by doing a simple blend (across one or two pixels) instead of just concatenating - at each level of the pyramid before reconstruction. Such a change improves the 'normal' output example just a little bit, and improves the pyramid-blended version substantially, by generating a much longer effective cross-blend in the lower pyramid layers. Though it may overcomplicate the example.
I followed the instruction for installing opencv from the tutorials and ended up with 2.4.x version and later encountered problem while going through the instructions.
There is no instruction for installing the 3.x version.
Sourceforge has only 2.4.x branches and Github repo also has only 2.4 branches on master.
It would be nice to have detailed instructions for installing 3.x version.
When I want to "make html" for sphinx v2.0.1 in windows, I found an error in the making which said could not find pngmath module for Sphinx.
I searched and find that I must change 'pngmath' to 'imgmath' in ./source/conf.py
It was solved. I just share my experience
Sincerely
For some odd reason, OpenCV throws a segmentation fault in the trackbar tutorial.
It still reports a segmentation fault when using gdb
, but it somehow doesn't when using VSCode's Debugger.
Going through by myself, the script only crashes python when using four or more Trackbars. Commenting out everything related to the switch
trackbar eliminated the issue, but when I attempted to add another trackbar, it crashed again.
Any insight into what may be causing this issue?
error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor @abidrahmank
following the "install opencv from source tutorial" i should install the ffmeg-devel package. but the package is not available:
[jan@localhost opencv]$ sudo yum install ffmpeg-devel
Fedora Modular 30 - x86_64 75 kB/s | 24 kB 00:00
Fedora Modular 30 - x86_64 - Updates 114 kB/s | 23 kB 00:00
Fedora 30 - x86_64 - Updates 23 kB/s | 24 kB 00:01
Fedora 30 - x86_64 31 kB/s | 24 kB 00:00
Kein Treffer für Argument: ffmpeg-devel
Fehler: Es konnte kein Treffer gefunden werden.: ffmpeg-devel
I have searched around on google and the best I could come up with was that ffmpeg should be placed in the PATH.
But even after doing so, I am not able to play video file as per the tutorial http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_video_display/py_video_display.html#display-video
Could do a tutorial on how to set up FFMpeg correctly ? Thanks.
I am using this function but it shows the following error:
contours, hierarchy = cv2.findContours(canny.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) :
error: ......\opencv-2.4.12\modules\core\src\matrix.cpp:236: error: (-215) step[dims-1] == (size_t)CV_ELEM_SIZE(flags) in function cv::Mat::create
Has it happened to anyone?
Hello, just tried your tutorial on python openCV (doing stuff on pattern matching, and your articles are great!), yet met a few errors:
a call to cv2.LINE_AA
causes an error - no-module-blah-blah… after digging a little around cv2, found that it should be cv2.CV_AA
.
Next culprit is img3 = cv2.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)
which returns module object has no attribute 'drawMatches'
and theres no drawMatches method in dir(cv2)... couldnot resolve this one and google is of little help here.
using cv2 version 2.4.7
installed via macports and pip
osx
My code is this :
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray, 1.1, 3)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
return frame
video_capture = cv2.VideoCapture(1)
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
ERROR:
runfile('C:/Users/Akhil/Desktop/OpenCV/Computer Vision A-Z/Module 1 - Face Recognition/face_recognition_nocomment.py', wdir='C:/Users/Akhil/Desktop/OpenCV/Computer Vision A-Z/Module 1 - Face Recognition')
Traceback (most recent call last):
File "<ipython-input-15-99eb78ea8252>", line 1, in <module>
runfile('C:/Users/Akhil/Desktop/OpenCV/Computer Vision A-Z/Module 1 - Face Recognition/face_recognition_nocomment.py', wdir='C:/Users/Akhil/Desktop/OpenCV/Computer Vision A-Z/Module 1 - Face Recognition')
File "C:\Users\Akhil\Anaconda3\envs\virtual_platform\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "C:\Users\Akhil\Anaconda3\envs\virtual_platform\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Akhil/Desktop/OpenCV/Computer Vision A-Z/Module 1 - Face Recognition/face_recognition_nocomment.py", line 21, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
error: ..\..\..\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function cv::ipp_cvtColor
What to do now :(
Hi, kindly remind that "img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)" should be converted into "cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)" to fix the bug "TypeError: 'NoneType' object has no attribute 'getitem'"
After installing python, numpy & matplotlib from given links and copying cv2.pyd, I get error:
opencv ImportError: numpy.core.multiarray failed to import
...while running the following code:
>>> import cv2
>>> print cv2.__version__
But, installing through pip, everything works fine.
Here is the code shown in the link provided.
mean_error = 0
for i in xrange(len(objpoints)):
imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)
tot_error += error
print "total error: ", mean_error/len(objpoints)
The mean_error
and tot_error
are messed up
If you look at
There should be an image output in the first section
img,contours,hierarchy = cv2.findContours(thresh, 1, 2)
otherwise it doesn't work, this is correct in earlier and later sections
The current link to stack overflow is listed as a relative path, instead of an absolute path. This issue is addressed in pull request #93 linked below.
If you find this issue to be legitimate, and my pull request (as linked) to be in the best interest of the project, please add a +1 reaction so this issue may be quickly resolved.
I have been following official documentation and while implementing surf I get this error
surf = cv2.SURF(400)
AttributeError: 'module' object has no attribute 'SURF'
Hey, I just stumbled over your documentation on Read the Docs.
I think I've spotted a typo in the URL: opencv-python-tutroals.readthedocs.org
Shouldn't it be opencv-python-tutorials.readthedocs.org ?
Nice regards
The link in README.md failed.
For official tutorials, please visit : http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html
It return 404 Not Found.
The code:
import cv2
import numpy as np
img = cv2.imread('home.jpg')
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT()
kp = sift.detect(gray,None)
img=cv2.drawKeypoints(gray,kp)
cv2.imwrite('sift_keypoints.jpg',img)
The error:
AttributeError: 'module' object has no attribute 'SIFT'
I am implementing an interactive GrabCut algorithm. When I apply the masks, the area corresponding to the mask is only highlighted.
The rectangle grabcut works well.
Then I load the mask using the interactive paint. It works well too.
Here is where the problem is. Part of the image is only selected. Can you upload code of implemented grabcut through masks please.(Not in your documentation)
Needless to say, other parts of the documentation is very awesome and I highly appreciate your efforts.
Hi I tried your code. it gives an error regarding no module SIFT for cv2 is available while cv2.FeautureDetector_create("SIFT") work. could you let me know why?
Code from https://github.com/abidrahmank/OpenCV2-Python-Tutorials/blob/master/source/py_tutorials/py_calib3d/py_calibration/py_calibration.rst fails to run
import numpy as np
import cv2
import glob
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
images = glob.glob('*.jpg')
for fname in images:
print 'Filename: ', fname
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (7,6),None)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners2)
# Draw and display the corners
#cv2.drawChessboardCorners(img, (7,6), corners2,ret)
#cv2.imshow('img',img)
#cv2.waitKey(500)
print 'Objects points: {0}, image points: {1}'.format(objpoints, imgpoints)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1])#,None,None)
cv2.destroyAllWindows()
OpenCV Error: Assertion failed (ni > 0 && ni == ni1) in collectCalibrationData, file /tmp/opencv20160107-29960-t5glvv/opencv-2.4.12/modules/calib3d/src/calibration.cpp, line 3193
Traceback (most recent call last):
File "calib.py", line 39, in <module>
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1])#,None,None)
cv2.error: /tmp/opencv20160107-29960-t5glvv/opencv-2.4.12/modules/calib3d/src/calibration.cpp:3193: error: (-215) ni > 0 && ni == ni1 in function collectCalibrationData
The color display differently using JupyterNoteBook using
plt.imshow(img)
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
since
(255,0,0) is color red
(0,0,255) is color blue
Thus, should be noted?
Hi,
While walking through the tutorial of the camera calibration I found two bugs (under "setup"):
The code lines:
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
and:
img = cv2.drawChessboardCorners(img, (7,6), corners2,ret)
always output none, instead I thing they should be just:
cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
cv2.drawChessboardCorners(img, (7,6), corners2,ret)
The functions modify the given img directly
Cheers,
Martijn
What license is this released under? May I suggest you use this and add appropriate info to the repo
mean_error = 0
for i in xrange(len(objpoints)):
imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)
tot_error += error
print "total error: ", mean_error/len(objpoints)
it should be :
mean_error = 0
tot_error = 0
for i in xrange(len(objpoints)):
imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(imgpoints[i], imgpoints2, cv2.NORM_L2) / len(imgpoints2)
tot_error += error
mean_error = tot_error / len(objpoints)
print "mean error: ", mean_error
print "total error: ", tot_error
New location (for box.jpg and box_in_scene.jpg):
I want to know distance metric used in knn , and how to normalize distance in n dimension .do i decide the threshold over the distance
Typo.
Hi,
I'm running through the OpenCV Drawing Functions tutorials and this link has a series of typos for me. http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html#drawing-functions
For example when I run
img = cv2.line(img,(0,0),(511,511),(255,0,0),5)
then cv2.line returns None and promptly overwrites img with None.
I'm in Python 2, not Python 3. Does the functionality change going from 2 to 3? Is this a typo for other poeple as well?
Hi,
I believe there is an error in the code given in the camera calibration tutorial.
When trying to find the chessboard corners, the line is currently :
ret, corners = cv2.findChessboardCorners(gray, (7,6), None)
But I believe it should be
ret, corners = cv2.findChessboardCorners(gray, (7,6), objp)
Because it is objp that is added to the objpoint list. If we read the code as it is, we always add the same initialized array objp that is never modified after creation.
In any case, thanks for the tutorials, they really help me!
can you tell me how to how can I matching SIFT features in same image in order to detect copy move forgery detection
on this page, at the bottom is a video link:
It also happens on the readthedocs version, basically what it's doing is adding github.com.... in front of the link, so that clicking it won't get you to youtube.
"It is more better and faster way to draw a group of lines than calling cv2.line() for each line."
I think the sentence could be improved by removing 'more better
'. Here is my suggested improvement.
"To draw groups of lines, calling cv2.polylines()
is better and faster than it is to call cv2.line()
for each line.
Thanks for writing the docs, I have found them useful.
best,
Hello,
I made the camera calibration lesson last night quite useful. Thanks for this.
However, I think there is a mistake in the subtopic about "Re projection error". In the code, mean_error is defined by the initial condition 0. Also, the end of the block of code is printed with a len(objpoints). But that code always "print 0". If It is possible, could you correct it?
Hi,
Please share the direct link to slow.flv used in Lukas-Kanade dense optical flow.
Thanks!
Stepping through the tutorials, and I was wondering about the following line: pts = pts.reshape((-1,1,2))
in the Drawing Functions tutorial. Is there a reason it should be rows x 1 x 2
shaped and not rows x 2
? When commenting out the reshape, I can see no change in the image produced so I'm curious what I'm missing. If it IS necessary, some more explanation would be lovely to have added.
The py_maths_tools is blank, but the SVD and PCA are really useful, may I see them anywhere else?
I tried using the function cv2.HoughCircles but it doesnt detect the hand drawn circle on the paper. Can anybody help me with this?
`
import numpy as np
import imutils
import cv2
image = cv2.imread("images/136_5cm.png")
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#gray = cv2.GaussianBlur(gray, (5, 5), 0)
print('hello')
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.4 ,100,)
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")
print(circles)
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circles:
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
cv2.circle(output, (x, y), r, (0, 255, 0), thickness=4, lineType=8, shift=0)
cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# show the output image
cv2.imshow("output", np.hstack([image, output]))
cv2.waitKey(0)`
In this path:
OpenCV2-Python-Tutorials/source/py_tutorials/py_imgproc/py_transforms/py_fourier_transform/py_fourier_transform.rst
There is an example that explains how to apply a filter in the frequency domain but there is an error, the filter MUST be transformed with FFT before multiplying it with the image to eliminate the ringing effect. I'm working on that, but if anyone knows how to do it, please fix that example.
I download the project and make html according to the readme. But there is something wrong.
My python version is:
platform : win-64
conda version : 4.3.16
conda is private : False
conda-env version : 4.3.16
conda-build version : 1.21.3
python version : 3.5.2.final.0
requests version : 2.12.4
The sphinx-err-m5iglv2b.log is paste below.
# Sphinx version: 1.3.1
# Python version: 3.5.2 (CPython)
# Docutils version: 0.13.1 release
# Jinja2 version: 2.9.4
# Last messages:
# writing output... [ 49%] py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations
# writing output... [ 50%] py_tutorials/py_imgproc/py_grabcut/py_grabcut
# writing output... [ 51%] py_tutorials/py_imgproc/py_gradients/py_gradients
# writing output... [ 53%] py_tutorials/py_imgproc/py_histograms/py_2d_histogram/py_2d_histogram
# writing output... [ 54%] py_tutorials/py_imgproc/py_histograms/py_histogram_backprojection/py_histogram_backprojection
# writing output... [ 55%] py_tutorials/py_imgproc/py_histograms/py_histogram_begins/py_histogram_begins
# writing output... [ 56%] py_tutorials/py_imgproc/py_histograms/py_histogram_equalization/py_histogram_equalization
# writing output... [ 58%] py_tutorials/py_imgproc/py_histograms/py_table_of_contents_histograms/py_table_of_contents_histograms
# writing output... [ 59%] py_tutorials/py_imgproc/py_houghcircles/py_houghcircles
# writing output... [ 60%] py_tutorials/py_imgproc/py_houghlines/py_houghlines
# Loaded extensions:
# sphinx.ext.todo (1.3.1) from D:\Anaconda3\lib\site-packages\sphinx\ext\todo.py
# alabaster (0.7.9) from D:\Anaconda3\lib\site-packages\alabaster\__init__.py
# sphinx.ext.doctest (1.3.1) from D:\Anaconda3\lib\site-packages\sphinx\ext\doctest.py
# sphinx.ext.coverage (1.3.1) from D:\Anaconda3\lib\site-packages\sphinx\ext\coverage.py
# sphinx.ext.pngmath (1.3.1) from D:\Anaconda3\lib\site-packages\sphinx\ext\pngmath.py
# sphinx.ext.extlinks (1.3.1) from D:\Anaconda3\lib\site-packages\sphinx\ext\extlinks.py
# sphinx.ext.autodoc (1.3.1) from D:\Anaconda3\lib\site-packages\sphinx\ext\autodoc.py
# sphinx.ext.intersphinx (1.3.1) from D:\Anaconda3\lib\site-packages\sphinx\ext\intersphinx.py
Traceback (most recent call last):
File "D:\Anaconda3\lib\site-packages\sphinx\cmdline.py", line 245, in main
app.build(opts.force_all, filenames)
File "D:\Anaconda3\lib\site-packages\sphinx\application.py", line 264, in build
self.builder.build_update()
File "D:\Anaconda3\lib\site-packages\sphinx\builders\__init__.py", line 245, in build_update
'out of date' % len(to_build))
File "D:\Anaconda3\lib\site-packages\sphinx\builders\__init__.py", line 316, in build
self.write(docnames, list(updated_docnames), method)
File "D:\Anaconda3\lib\site-packages\sphinx\builders\__init__.py", line 354, in write
self._write_serial(sorted(docnames), warnings)
File "D:\Anaconda3\lib\site-packages\sphinx\builders\__init__.py", line 362, in _write_serial
self.write_doc(docname, doctree)
File "D:\Anaconda3\lib\site-packages\sphinx\builders\html.py", line 439, in write_doc
self.docwriter.write(doctree, destination)
File "D:\Anaconda3\lib\site-packages\docutils\writers\__init__.py", line 80, in write
self.translate()
File "D:\Anaconda3\lib\site-packages\sphinx\writers\html.py", line 53, in translate
self.document.walkabout(visitor)
File "D:\Anaconda3\lib\site-packages\docutils\nodes.py", line 187, in walkabout
visitor.dispatch_departure(self)
File "D:\Anaconda3\lib\site-packages\docutils\nodes.py", line 1895, in dispatch_departure
return method(node)
File "D:\Anaconda3\lib\site-packages\docutils\writers\_html_base.py", line 671, in depart_document
assert not self.context, 'len(context) = %s' % len(self.context)
AssertionError: len(context) = 1
In README
http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html
doesn't work.
https://opencv-python-tutroals.readthedocs.org/en/latest/index.html
you spelled 'tutorials' wrong.
Hi,
The readme says that a build foder exists... But it does not appear to be there. only a source folder. Obviously I can still access you files but would be great to have this explained!
Hello guys,
nice work at the manuals and tutorials.
About the link to ipython profile there is a error:
Instead
http://pynash.org/2013/03/06/timing-and-profiling.html
the correct link is:
http://pynash.org/2013/03/06/timing-and-profiling/
Hope it will be helpfull
hi there,
first of all many many thanks for all the great tutorial! i really appreciate it, it is such a great resource for learning openCV with python!
but unfortunately it seems that all images of the online version (https://opencv-python-tutroals.readthedocs.org/en/latest/index.html) are broken ... any chance to have them back? :)
best,
benedikt
Can you please what is significance of every parameters of cv2.drawContours() in readme .
add the following code
if ret == False: # check end of the video by checking this return value.
break
after
ret, frame = cap.read()
if not doing this, there will be a fatal error when play a video
New location (for box.jpg and box_in_scene.jpg):
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.