Reputation: 261
I want to create a video from images using opencv.
The strange problem is that if i will write image (bmp)
to disk and then load (cv.LoadImage) it it renders fine, but
when i try to load image from StringIO and convert
it to IplImage, it turns video to blue.
Heres the code:
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
Upvotes: 0
Views: 574
Reputation: 3486
OpenCV opens the images default with BGR
, in PIL that is not the case. That resulted in your problem. A solution is already given, but I wrote this post so you can learn the reason behind it and maybe derive your own solution for this case and possibly any case in future.
Upvotes: 1
Reputation: 261
I found solution 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())
Upvotes: 0