I'm new to Open CV and python, and I've been facing a problem:
I've been doing a project on my Raspberry Pi where the webcam takes a grey scale image, removes the background, and saves it in a folder.
This is used by a machine learning algorithm to detect the object in the image.
The webcam is fixed at a particular point so I first take an image of the background and then take a picture of the object. The background is then removed from the object and it looks fine.
But if I repeat the process and overwrite the image, it becomes blurred.
This effect keeps happening until after about three or four shots the image becomes blurry and my program cant identify the object in it.
My code is:
#get Background
import cv2
cam = cv2.videoCapture(0)
ret, frame = cam.read()
if ret:
img_name = '/home/pi/Desktop/background.png'
grey_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(img_name, grey_img)
print('{} written'.format(img_name))
cam.release()
#takeImage
import cv2
import numpy as np
ret, frame = cam.read()
back = cv2.imread('/home/pi/Desktop/background.png')
if ret:
img_name = '/home/pi/Desktop/img_capture.png'
grey_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(img_name, grey_img)
grey_obj = cv2.subtract(cv2.imread(img_name), back)
cv2.imwrite(img_name, grey_obj)
print('{} written'.format(img_name))
cam.release()
I'm using a Logitech webcam but I'm not sure of the exact model
Please help me out, and thanks in advance.
Clear at the start:
Not so much:
Not at all:
Related
I am a complete beginner with coding and needed to code a few lines of code for getting pictures from a USB camera for a research project that i am responsible for. admittingly i took help of a few source codes from a few blogs online, they did show a couple of errors but most of them were resolved except this one that keeps popping up no matter what i do. does anyone have any idea where exactly the problem could be arising from? all the errors in the previous lines of code seem to be dealt with. I really need to get this right as this project decides my bacheklor thesis
the following was the code that i used, even though i am really really dumb with this stuff:
`
#new camera code
import cv2
import imutils
import time
#loop for taking picture and saving
cap = cv2.VideoCapture(0)
frame = cap.read()
def takePicture():
global showimg
(frame) = cap.read()
showimg=frame
return image
cv2.imshow('image', img)
cv2.imshow('img1',showimg) # display the captured image
cv2.waitKey(1)
time.sleep(0.3) # Wait 300 miliseconds
image ='C:/Users/whale/Desktop/REMOVE/capture.png'
cv2.imwrite(image, frame)
img = cv2.imread('no-such-file.jpg', 0)
cap.release()
print(takePicture())
`
There are a few issues with your code:
The takePicture() function is not returning anything. It needs to return showimg instead of image.
The line global showimg (frame) = cap.read() should be changed to global showimg, frame; frame = cap.read().
The line img = cv2.imread('no-such-file.jpg', 0) should be removed as it is not being used and it may cause confusion.
The line print(takePicture()) should be changed to takePicture() as the function already displays the image.
Here's the correct code:
#new camera code
import cv2
import imutils
import time
#loop for taking picture and saving
cap = cv2.VideoCapture(0)
def takePicture():
global showimg, frame
frame = cap.read()
showimg = frame
cv2.imshow('image', showimg) # display the captured image
cv2.waitKey(1)
time.sleep(0.3) # Wait 300 miliseconds
image ='C:/Users/whale/Desktop/REMOVE/capture.png'
cv2.imwrite(image, frame)
return showimg
takePicture()
cap.release()
I am using opencv in Python to play a video file full screen. The video is 4:3 aspect ratio, and imshow is by default maintaining the aspect ratio by creating a gray pillarbox along the right side of the screen.
I have not been succesfull in finding any documentation about how to manipulate this – i.e. how to change the color of the pillarbox / what I would presume is the default color of the empty window at the OS level? If changing the color is not explicitly supported by opencv is there a workaround? i.e. draw a black rectangle underneith the video frame?
#!/usr/bin/env python3
import cv2 as cv
cap = cv.VideoCapture("video.mp4")
while(cap.isOpened()):
ret,frame = cap.read()
frame = cv.resize(frame,(720,480))
cv.imshow("video", frame)
cv.namedWindow("video", cv.WND_PROP_FULLSCREEN)
cv.setWindowProperty("video", cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
if cv.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
I'm trying my hands on OpenCV with Python and 'am kind of stuck.
I want to find specific trackers from every frame of a live camera and detect changes in the environment with a tracker of different color (say red).
Right now, my code takes a frame of my video which I select, and shows trackers which are too much to understand.
Can you help me in fixing this code?
import numpy as np
import cv2
from matplotlib import pyplot as plt
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)
# Initiate feature detector
orb = cv2.FastFeatureDetector_create()
# find the keypoints with ORB
kp = orb.detect(gray)
img2 = cv2.drawKeypoints(frame, kp, outImage=None, color=(0, 255, 0), flags=0)
plt.imshow(img2), plt.show()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
This is my image without an object (bottle)
This is me with an object
Now what I want to track changes in between the images (with bottle and without bottle), i.e changes in environment of an image should be tracked live on videocam!
I've showed in various ways how to take images with a webcam in Python (see How can I take camera images with Python?). You can see that the images taken with Python are considerably darker than images taken with JavaScript. What is wrong?
Image example
The image on the left was taken with http://martin-thoma.com/html5/webcam/, the one on the right with the following Python code. Both were taken with the same (controlled) lightning situation (it was dark outside and I only had some electrical lights on) and the same webcam.
Code example
import cv2
camera_port = 0
camera = cv2.VideoCapture(camera_port)
return_value, image = camera.read()
cv2.imwrite("opencv.png", image)
del(camera) # so that others can use the camera as soon as possible
Question
Why is the image taken with Python image considerably darker than the one taken with JavaScript and how do I fix it?
(Getting a similar image quality; simply making it brighter will probably not fix it.)
Note to the "how do I fix it": It does not need to be opencv. If you know a possibility to take webcam images with Python with another package (or without a package) that is also ok.
Faced the same problem. I tried this and it works.
import cv2
camera_port = 0
ramp_frames = 30
camera = cv2.VideoCapture(camera_port)
def get_image():
retval, im = camera.read()
return im
for i in xrange(ramp_frames):
temp = camera.read()
camera_capture = get_image()
filename = "image.jpg"
cv2.imwrite(filename,camera_capture)
del(camera)
I think it's about adjusting the camera to light. The former
former and later images
I think that you have to wait for the camera to be ready.
This code works for me:
from SimpleCV import Camera
import time
cam = Camera()
time.sleep(3)
img = cam.getImage()
img.save("simplecv.png")
I took the idea from this answer and this is the most convincing explanation I found:
The first few frames are dark on some devices because it's the first
frame after initializing the camera and it may be required to pull a
few frames so that the camera has time to adjust brightness
automatically.
reference
So IMHO in order to be sure about the quality of the image, regardless of the programming language, at the startup of a camera device is necessary to wait a few seconds and/or discard a few frames before taking an image.
Tidying up Keerthana's answer results in my code looking like this
import cv2
import time
def main():
capture = capture_write()
def capture_write(filename="image.jpeg", port=0, ramp_frames=30, x=1280, y=720):
camera = cv2.VideoCapture(port)
# Set Resolution
camera.set(3, x)
camera.set(4, y)
# Adjust camera lighting
for i in range(ramp_frames):
temp = camera.read()
retval, im = camera.read()
cv2.imwrite(filename,im)
del(camera)
return True
if __name__ == '__main__':
main()
i'm making a face/eyes recognition software with python, using the opecv library, in a Raspberry and capturing the video with a rpi camera.
I've already written the code, and everything works fine on my PC. Actually it works fine on my Raspberry as well, but the problem is about the speed of it. On my Raspberry it goes really slow.
Here's the code anyway:
#import numpy as np
import cv2
dims = (240, 120) # webcam dimensions
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 360);
face_cascade = cv2.CascadeClassifier('/home/pi/Desktop/Raspberry/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/home/pi/Desktop/Raspberry/haarcascade_eye.xml')
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
#frame = cv2.imread('./Data/viola.jpg')
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect the face
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
print(len(faces))
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)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
As you can see i've set the resolution to 640X480, and with this the video shows about one frame every 1-2 seconds. If i don't specify the resolution it gets me a really small window in where there's my output. I have to say that i connect to my Raspberry throw SSH, but even if i record the video, and then i watch it on my PC is very slow. What i want to say is that it doesn't seem a problem given by the SSH tunnel.
To use the opencv's VideoCapture feature i had to inslall the UV4L driver, following this guide: http://www.linux-projects.org/modules/sections/index.php?op=viewarticle&artid=14 .
I saw many people using this method of capturing a video with opencv in raspberry, and nobody say anything about the framerate. Anyone know what should i do to have it faster?
PS i know that may be this is not the place in where we can make questions like this. But i don't really know where to ask it.
You are capturing the uncompressed frames, set this property to capture compressed frames, cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
ex:
#import numpy as np
import cv2
dims = (240, 120) # webcam dimensions
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 360)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
.......