2020년 7월 9일 목요일

[python] merge webtoon file


1. Merge WebToon File


import os
import codecs
import numpy as np
import cv2
from PIL import Image

def cv2_imread( filePath ) :
 with open( filePath.encode("utf-8"), "rb") as f:
  image = bytearray(f.read())
  nparray = np.asarray(image, dtype = np.uint8)
  return cv2.imdecode(nparray , cv2.IMREAD_UNCHANGED)

def cv2_imread2( filePath ) :
 with open( filePath.encode("utf-8"), 'rb') as f:
  image = f.read()
  nparray = np.fromstring(image, dtype = np.uint8)
  return cv2.imdecode(nparray , cv2.IMREAD_UNCHANGED)

def cv2_imwrite( filePath, cv_image ) :
 rv, im_jpg = cv2.imencode( filePath[-4:], cv_image)
 with open( filePath, 'wb') as f:
  f.write(im_jpg.tobytes())
 



if __name__ == "__main__":
 base_dir = r"d:\Ebook\웹툰\수화"
 sub_dirs = os.listdir(base_dir)
 for sub_dir in sub_dirs:
  image_list = []
  height = 0
  index = 1
  sub_dir_path = os.path.join(base_dir,sub_dir)
  image_files = os.listdir(sub_dir_path)
  for image_file in image_files:
   image_file_name = os.path.join(sub_dir_path,image_file)
   print(image_file_name )
   img = cv2_imread(image_file_name)
   h, w = img.shape[:2]
   if h + height < 65000:
    image_list.append(img)
    height = height + h
   else:
    image_merged = cv2.vconcat( image_list )
    merged_file_name = sub_dir_path + '_' + str(index) + '.jpg'
    print( '->', merged_file_name)
    cv2_imwrite(merged_file_name, image_merged)
    image_list = []
    height = 0
    index = index + 1
  if height > 0:
   image_merged = cv2.vconcat( image_list )
   merged_file_name = sub_dir_path + '_' + str(index) + '.jpg'
   print( '->', merged_file_name)
   cv2_imwrite(merged_file_name, image_merged)

댓글 없음:

댓글 쓰기