转换为视频后,图像帧的强度值发生变化

时间:2019-03-20 08:57:58

标签: python opencv image-processing video-processing

我正在使用openCV创建具有特定模式的视频。我的一种尺寸为35x35的图案如下所示

pattern

和基础矩阵中的相应数字条目如下所示

enter image description here

我的想法是将图案叠加到大小260x346的白色背景上,并创建一个视频,其中图案水平移动。第一帧看起来像这样

enter image description here

我使用具有以下功能的openCV创建视频

def move_square(pattern, background):
    '''
    The function creates a video of the pattern moving horizontally over a given background

    Parameters:
    -----------
    pattern: <np.array, 35x35>
        The pattern supposed to move over the background
    background: <np.array, 260x346>
        A white background of the given size 
    '''
    fourcc = VideoWriter_fourcc(*'MP42')
    video = VideoWriter('./videos/moving_pattern_for_sampling_exp.avi', fourcc, 30, (346, 260))
    background[112:147, 0:35] = pattern
    frame = background

    for _ in range(0, 346-30):
        video.write(cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB))
        shifted_frame =  np.roll(frame, 1, axis=1)
        frame = shifted_frame
        video.write(frame)

    cv2.destroyAllWindows()
    video.release()

但是,如果我使用以下代码片段阅读了上面视频的帧

vidcap = cv2.VideoCapture('videos/moving_pattern_for_sampling_exp.avi')
success,image = vidcap.read()
count = 0

while success:
  cv2.imwrite("test/frame%d.jpg" % count, image)     # save frame as JPEG file      
  success,image = vidcap.read()
  print('Read a new frame: ', success)
  count += 1

im = cv2.imread('test/frame1.jpg')
img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
np.savetxt("image.csv", np.asarray(img),fmt='%i', delimiter=",")

现在查看框架,框架中图案的值不同于它们的原始值。

enter image description here

本应设置为255的白色位置现在也已设置为252。这些差异的原因可能是什么?

1 个答案:

答案 0 :(得分:2)

以JPEG格式保存图像时,质量会下降,从而导致精度下降。 这是JPEG压缩的示例(您可以找到完整图片here):

No compression Compression

您可以观察到鸟类和木材的质量下降(在完整图像中)。

正如@Mark Setchell所建议的那样,您可以使用PNG来避免这种情况,但是请注意,图像中的颜色变化越多,文件就越大。

如果有帮助,this wikipedia article简要介绍了常见的文件格式。