图像到视频 - 转换为IplImage使视频变为蓝色

时间:2012-09-14 06:25:59

标签: python opencv

我想使用opencv从图像创建视频。

奇怪的问题是如果我会写图像(bmp) 到磁盘,然后加载(cv.LoadImage)它渲染得很好,但是 当我尝试从StringIO加载图像并转换 它是IplImage,它将视频转为蓝色。

下面是代码:

import StringIO
output = StringIO.StringIO()
FOREGROUND = (0, 0, 0)
TEXT = 'MY TEXT'
font_path = 'arial.ttf'
font = ImageFont.truetype(font_path, 18, encoding='unic')
text = TEXT.decode('utf-8')
(width, height) = font.getsize(text)
# Create with background with place for text
w,h=(600,600)
contentimage=Image.open('0.jpg')
background=Image.open('background.bmp')

x, y = contentimage.size

# put content onto background
background.paste(contentimage,(((w-x)/2),0))
draw = ImageDraw.Draw(background)
draw.text((0,0), text, font=font, fill=FOREGROUND)

pi = background
pi.save(output, "bmp")
#pi.show()   #shows image in full color
output.seek(0)
pi= Image.open(output)
print pi, pi.format, "%dx%d" % pi.size, pi.mode
cv_im = cv.CreateImageHeader(pi.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(cv_im, pi.tostring())
print pi.size, cv.GetSize(cv_im)
w = cv.CreateVideoWriter("2.avi", cv.CV_FOURCC('M','J','P','G'), 1,(cv.GetSize(cv_im)[0],cv.GetSize(cv_im)[1]), is_color=1)
for i in range(1,5):
    cv.WriteFrame(w, cv_im)
del w

2 个答案:

答案 0 :(得分:1)

OpenCV打开图像默认为BGR,在PIL中不是这种情况。这导致了你的问题。已经给出了一个解决方案,但是我写了这篇文章,这样你就可以了解它背后的原因,也许可以为这个案例找到你自己的解决方案,也可能是将来的任何案例。

答案 1 :(得分:0)

我找到了解决方案 http://choco-lue.blogspot.com/2010/04/python-image-library-part-2-opencv.html

import Image, cv
pi = Image.open('building.jpg')       # PIL image
cv_im = cv.CreateImageHeader(pi.size, cv.IPL_DEPTH_8U, 3)
r,g,b=pi.split()
pi2=Image.merge("RGB",(b,g,r))
cv.SetData(cv_im, pi2.tostring())