>  기사  >  백엔드 개발  >  Python의 gif 동적 그래픽 분석 및 합성 소개

Python의 gif 동적 그래픽 분석 및 합성 소개

不言
不言앞으로
2018-12-31 09:24:274146검색

이 기사의 내용은 Python의 gif 동적 이미지 처리에 대한 분석 및 합성 작업에 대한 소개입니다. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

이 기사의 예에서는 Python 이미지 처리에서 gif 동적 이미지를 분석하고 합성하는 방법을 설명합니다. 참고하실 수 있도록 자세한 내용은 다음과 같습니다.

Gif 애니메이션은 이제 흔한 일이며, 친구들 사이에서는 의견이 다를 때 종종 싸우기도 합니다. 여기에서는 Python을 사용하여 gif 이미지를 구문 분석하고 생성하는 방법을 소개하겠습니다.

1.gif 애니메이션 합성

아래와 같이 gif 애니메이션입니다.

Gif 애니메이션은 PIL 이미지 모듈을 이용하여 분석할 수 있습니다. 구체적인 코드는 다음과 같습니다. PIL图像模块即可,具体代码如下:

#-*- coding: UTF-8 -*-
import os
from PIL import Image
def analyseImage(path):
  '''
  Pre-process pass over the image to determine the mode (full or additive).
  Necessary as assessing single frames isn't reliable. Need to know the mode
  before processing all frames.
  '''
  im = Image.open(path)
  results = {
    'size': im.size,
    'mode': 'full',
  }
  try:
    while True:
      if im.tile:
        tile = im.tile[0]
        update_region = tile[1]
        update_region_dimensions = update_region[2:]
        if update_region_dimensions != im.size:
          results['mode'] = 'partial'
          break
      im.seek(im.tell() + 1)
  except EOFError:
    pass
  return results
def processImage(path):
  '''
  Iterate the GIF, extracting each frame.
  '''
  mode = analyseImage(path)['mode']
  im = Image.open(path)
  i = 0
  p = im.getpalette()
  last_frame = im.convert('RGBA')
  try:
    while True:
      print "saving %s (%s) frame %d, %s %s" % (path, mode, i, im.size, im.tile)
      '''
      If the GIF uses local colour tables, each frame will have its own palette.
      If not, we need to apply the global palette to the new frame.
      '''
      if not im.getpalette():
        im.putpalette(p)
      new_frame = Image.new('RGBA', im.size)
      '''
      Is this file a "partial"-mode GIF where frames update a region of a different size to the entire image?
      If so, we need to construct the new frame by pasting it on top of the preceding frames.
      '''
      if mode == 'partial':
        new_frame.paste(last_frame)
      new_frame.paste(im, (0,0), im.convert('RGBA'))
      new_frame.save('%s-%d.png' % (''.join(os.path.basename(path).split('.')[:-1]), i), 'PNG')
      i += 1
      last_frame = new_frame
      im.seek(im.tell() + 1)
  except EOFError:
    pass
def main():
  processImage('test_gif.gif')
if __name__ == "__main__":
  main()

解析结果如下,由此可见改动态图实际上是由14张相同分辨率的静态图组合而成

二、gif动态图的合成

gif图像的合成,使用imageio

#-*- coding: UTF-8 -*-
import imageio
def create_gif(image_list, gif_name):
  frames = []
  for image_name in image_list:
    frames.append(imageio.imread(image_name))
  # Save them as frames into a gif
  imageio.mimsave(gif_name, frames, 'GIF', duration = 0.1)
  return
def main():
  image_list = ['test_gif-0.png', 'test_gif-2.png', 'test_gif-4.png',
         'test_gif-6.png', 'test_gif-8.png', 'test_gif-10.png']
  gif_name = 'created_gif.gif'
  create_gif(image_list, gif_name)
if __name__ == "__main__":
  main()

분석 결과는 실제로 수정된 애니메이션임을 알 수 있습니다. 동일한 해상도의 이미지 14개로 구성

의

2. gif 동적 이미지 합성

gif 이미지 합성은 imageio 라이브러리(https://pypi.python.org/pypi/imageio)를 사용하세요.

🎜코드는 다음과 같습니다: 🎜rrreee🎜here , 첫 번째 단계에서 파싱된 이미지 중 8개 이미지를 사용하여 0.1초 간격으로 새로운 gif 동적 이미지가 다음과 같이 합성됩니다. 🎜🎜🎜🎜🎜🎜🎜🎜

위 내용은 Python의 gif 동적 그래픽 분석 및 합성 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 jb51.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제