I am trying to use background Substractor module in opencv. I am referring this blog. I am not able to use it because I again and again get the error message 'module' object has no attribute 'createBackgroundSubtractorMOG' , I have go-ogled through all the answers to this problem and I have tried using all the substrings possible like - createBackgroundSubtractor , BackgroundSubtractor , createBackgroundSubtractorMOG2 etc. but I again get the same error message. I am using -
opencv 3.0.0
python 2.7.10
ubuntu 15.10
here's my code--
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG(detectShadows=True)
while(1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
cv2.imshow('frame', fgmask)
k = cv2.waitKey(0)
if(k == 27):
break
cap.release()
cv2.destroyAllWindows()
Got my question solved. What i did , I opened python command line and wrote dir(cv2) and it listed me all the functions I can call and there I found BackgroundSubtractorMOG and it worked!
Related
I am using imageio to write png images to file.
import numpy as np
import matplotlib.cm as cm
import imageio # for saving the image
import matplotlib as mpl
hm_colors = ['blue', 'white','red']
cmap = mpl.colors.LinearSegmentedColormap.from_list('bwr', hm_colors)
data = np.array([[1,2,3],[5,6,7]])
norm = mpl.colors.Normalize(vmin=-3, vmax=3)
colormap = cm.ScalarMappable(norm=norm, cmap=cmap)
im = colormap.to_rgba(data)
# scale the data to a width of w pixels
im = np.repeat(im, w, axis=1)
im = np.repeat(im, h, axis=0)
# save the picture
imageio.imwrite("my_img.png", im)
This process is performed automatically and I noticed some Error messages saying:
Error closing: 'Image' object has no attribute 'fp'.
Before this message I get warning:
/usr/local/lib/python2.7/dist-packages/imageio/core/util.py:78: UserWarning: Lossy conversion from float64 to uint8, range [0, 1] dtype_str, out_type.__name__))
However, the images seem to be generated and saved just fine.
I can't find data to recreate this message.
Any idea why I get this error and why it doesn't noticeably affect the results? I don't use PIL.
One possible reason could come from using this in Celery.
Thanks!
L.
I encountered the same issue using imageio.imwrite in Python 3.5. It's a fairly harmless except for the fact that that it's stopping garbage collection and leading to excessive memory usage when writing thousands of images. The solution was to use the PIL module, which is a dependency of imageio. The last line of your code should read:
from PIL import Image
image = Image.fromarray(im)
image.save('my_img.png')
I am new to Python and have been following a basic tutorial (https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_calib3d/py_depthmap/py_depthmap.html#py-depthmap) for creating a disparity map from two images, but I have had several errors.
I am using Python 2.7, OpenCV 3.3.0, matplotlib 1.3, numpy 1.10.2
This is my code v1:
import numpy as np
import cv2
from matplotlib import pyplot as plt
imgL = cv2.imread("C:\Python27\tsukuba_l.png,0")
imgR = cv2.imread("C:\Python27\tsukuba_r.png,0")
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'gray')
plt.show()
I corrected the stereoBM function from the tutorial to match the latest openCV version cv2.createStereoBM to cv2.StereoBM_create and got an error. (-211) SADWindowSize must be odd, be within 5..255 and not be larger than image width or height in function on the 2nd to last line (disparity=...). I tried reducing the block size but there was still an error, I have checked the image pathways are correct and both images are the same size.
I then have attempted to use StereoSGBM_create instead, v2 code:
import numpy as np
import cv2
from matplotlib import pyplot as plt
imgL = cv2.imread("C:\Python27\tsukuba_l.png,0")
imgR = cv2.imread("C:\Python27\tsukuba_r.png,0")
stereo = cv2.StereoSGBM_create(minDisparity=5, numDisparities=16, blockSize=5)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'gray')
plt.show()
However this returns:
TypeError: Image data can not convert to float.
Any reason why these errors maybe occurring?
Typo error :
change
imgL = cv2.imread("C:\Python27\tsukuba_l.png,0")
imgR = cv2.imread("C:\Python27\tsukuba_r.png,0")
to
imgL = cv2.imread("C:\Python27\tsukuba_l.png",0)
imgR = cv2.imread("C:\Python27\tsukuba_r.png",0)
or better :
imgL = cv2.imread("C:\Python27\tsukuba_l.png",cv2.IMREAD_GRAYSCALE)
imgR = cv2.imread("C:\Python27\tsukuba_r.png",cv2.IMREAD_GRAYSCALE)
from cv2.imread
Warning Even if the image path is wrong, it won’t throw any error,
I install cv2 using pip command but it give error No matching
distribution found for cv2.
Below my is code
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Install opencv or cv2 using pip
import cv2
import numpy as np
cap = cv2.VideoCapture('traffic.avi')
retval, frame = cap.read()
print retval
================ RESTART: J:\Python For DIP\traffic_video.py ================
False
>>>
The Value of retval is always False, which means the video is not read by the command. It must be True to read frames. I don't know what to do. However when I use my default webcam it turns to be True. I tried many videos and the same problem appears. Note: I have installed the ffmpeg correctly.
Note: This is not the full code, in this step I am only validating cap.read() either True or False
This method is guaranteed 100%
first of all check your version of OpenCV, say for instance 2.4.11. you can check it by typing the following commands in your Python Shell:
>>> from cv2 import __version__
>>> __version__
'2.4.11'
>>>
Then go to C:\opencv\build\x86\vc12\bin and copy opencv_ffmpeg2411.dll.
Finally go to root directory of Python ex: C:\Python27 and paste opencv_ffmpeg2411.dll in it
check the name of the file opencv_ffmpeg2411.dll, whether the version
of opencv is written or not, if not do the following
opencv_ffmpeg(version of your opencv without dots).dll
After that create a new Python file and copy this code and paste it loading your own video
import numpy as np
import cv2
# Capture video from file
cap = cv2.VideoCapture('your video')
while True:
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(30) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
you will have an output video for example like this:
Result
Finding the root directory of Python can be a little tricky. I am using an Enthought distribution and, at first, pasted the opencv_ffmpeg file into the wrong Python directory.
WRONG:
C:\Users\USERNAME\AppData\Local\Programs\Python\Python35-32
RIGHT:
C:\Users\USERNAME\AppData\Local\Enthought\Canopy\User
Long story short, make sure you find the right Python directory.
Case 1: This code runs fine:
import numpy as np
import cv2
from matplotlib import pyplot as plt
imgL = cv2.imread('lena.png', 0)
imgR = cv2.imread('lena.png', 0)
stereo = cv2.StereoBM(0, ndisparities=16, SADWindowSize=15)
stereo.compute(imgL, imgR)
Case 2: But this fails on the last line:
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('lena.png', 1)
imgR = img[:,:,2]
imgL = img[:,:,1]
stereo = cv2.StereoBM(0, ndisparities=16, SADWindowSize=15)
stereo.compute(imgL, imgR)
The error says:
error: /build/buildd/opencv-2.3.1/modules/calib3d/src/stereobm.cpp:802: error: (-211) SADWindowSize must be odd, be within 5..255 and be not larger than image width or height in function findStereoCorrespondenceBM
The really strange thing is that it fails with the same message even if I put following two lines right in front of the imgR = and imgL = starting lines, i.e.:
img = cv2.imread('lena.png', 1)
img[:,:,2] = cv2.imread('lena.png', 0)
img[:,:,1] = cv2.imread('lena.png', 0)
imgR = img[:,:,2]
imgL = img[:,:,1]
I'm still quite new to Python so maybe its a misunderstanding: Can somebody explain why case 1 works but case 2 gives me an error?
It looks like it's a bug in old OpenCV version.
Part of OpenCV 2.4.4 changelog:
Numerous bug fixes, and optimizations, including in: blendLinear, square samples, erode/dilate, Canny, convolution fixes with AMD FFT library, mean shift filtering, Stereo BM.
Most likely using 2.4.4 or any higher version (I suggest that you use the latest stable release) will solve your problem.