为什么 Python 拍摄的网络摄像头图像如此暗?

Why are webcam images taken with Python so dark?

我在 Python 中以各种方式展示了如何使用网络摄像头拍摄图像(参见 How can I take camera images with Python?)。您可以看到使用 Python 拍摄的图像比使用 JavaScript 拍摄的图像暗得多。怎么了?

图片示例

左边的图片是用http://martin-thoma.com/html5/webcam/拍的,右边的是用下面的Python代码拍的。两者都是在相同的(受控的)闪电情况下拍摄的(外面很黑,我只开着一些电灯)和相同的网络摄像头。

代码示例

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

问题

为什么用 Python 拍摄的图像比用 JavaScript 拍摄的图像暗得多,我该如何解决?

(获得相似的图像质量;简单地提高亮度可能无法解决问题。)

"how do I fix it"注意事项:不需要是opencv。如果您知道可以使用 Python with another package(或不使用软件包)拍摄网络摄像头图像,那也可以。

我认为你必须等待相机准备好。

这段代码对我有用:

from SimpleCV import Camera
import time
cam = Camera()
time.sleep(3)
img = cam.getImage()
img.save("simplecv.png")

我的想法来自 this answer,这是我发现的最有说服力的解释:

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

所以恕我直言,为了确保图像质量,无论使用何种编程语言,在相机设备启动时都需要等待几秒钟 and/or 在拍摄前丢弃几帧图片。

遇到了同样的问题。我试过了,效果很好。

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)

我认为这是关于将相机调整为光线。前者 former and later 图片

整理 Keerthana 的答案后我的代码如下所示

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()