movie2movie.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import copy
  2. import os
  3. import shutil
  4. import cv2
  5. import gradio as gr
  6. import modules.scripts as scripts
  7. from modules import images
  8. from modules.processing import process_images
  9. from modules.shared import opts
  10. from PIL import Image
  11. import numpy as np
  12. _BASEDIR = "/controlnet-m2m"
  13. _BASEFILE = "animation"
  14. def get_all_frames(video_path):
  15. if video_path is None:
  16. return None
  17. cap = cv2.VideoCapture(video_path)
  18. frame_list = []
  19. if not cap.isOpened():
  20. return
  21. while True:
  22. ret, frame = cap.read()
  23. if ret:
  24. frame_list.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
  25. else:
  26. return frame_list
  27. def get_min_frame_num(video_list):
  28. min_frame_num = -1
  29. for video in video_list:
  30. if video is None:
  31. continue
  32. else:
  33. frame_num = len(video)
  34. print(frame_num)
  35. if min_frame_num < 0:
  36. min_frame_num = frame_num
  37. elif frame_num < min_frame_num:
  38. min_frame_num = frame_num
  39. return min_frame_num
  40. def pil2cv(image):
  41. new_image = np.array(image, dtype=np.uint8)
  42. if new_image.ndim == 2:
  43. pass
  44. elif new_image.shape[2] == 3:
  45. new_image = new_image[:, :, ::-1]
  46. elif new_image.shape[2] == 4:
  47. new_image = new_image[:, :, [2, 1, 0, 3]]
  48. return new_image
  49. def save_gif(path, image_list, name, duration):
  50. tmp_dir = path + "/tmp/"
  51. if os.path.isdir(tmp_dir):
  52. shutil.rmtree(tmp_dir)
  53. os.mkdir(tmp_dir)
  54. for i, image in enumerate(image_list):
  55. images.save_image(image, tmp_dir, f"output_{i}")
  56. os.makedirs(f"{path}{_BASEDIR}", exist_ok=True)
  57. image_list[0].save(f"{path}{_BASEDIR}/{name}.gif", save_all=True, append_images=image_list[1:], optimize=False, duration=duration, loop=0)
  58. class Script(scripts.Script):
  59. def title(self):
  60. return "controlnet m2m"
  61. def show(self, is_img2img):
  62. return True
  63. def ui(self, is_img2img):
  64. # How the script's is displayed in the UI. See https://gradio.app/docs/#components
  65. # for the different UI components you can use and how to create them.
  66. # Most UI components can return a value, such as a boolean for a checkbox.
  67. # The returned values are passed to the run method as parameters.
  68. ctrls_group = ()
  69. max_models = opts.data.get("control_net_max_models_num", 1)
  70. with gr.Group():
  71. with gr.Accordion("ControlNet-M2M", open = False):
  72. duration = gr.Slider(label=f"Duration", value=50.0, minimum=10.0, maximum=200.0, step=10, interactive=True, elem_id='controlnet_movie2movie_duration_slider')
  73. with gr.Tabs():
  74. for i in range(max_models):
  75. with gr.Tab(f"ControlNet-{i}"):
  76. with gr.TabItem("Movie Input"):
  77. ctrls_group += (gr.Video(format='mp4', source='upload', elem_id = f"video_{i}"), )
  78. with gr.TabItem("Image Input"):
  79. ctrls_group += (gr.Image(source='upload', brush_radius=20, mirror_webcam=False, type='numpy', tool='sketch', elem_id=f'image_{i}'), )
  80. ctrls_group += (gr.Checkbox(label=f"Save preprocessed", value=False, elem_id = f"save_pre_{i}"),)
  81. ctrls_group += (duration,)
  82. return ctrls_group
  83. def run(self, p, *args):
  84. # This is where the additional processing is implemented. The parameters include
  85. # self, the model object "p" (a StableDiffusionProcessing class, see
  86. # processing.py), and the parameters returned by the ui method.
  87. # Custom functions can be defined here, and additional libraries can be imported
  88. # to be used in processing. The return value should be a Processed object, which is
  89. # what is returned by the process_images method.
  90. contents_num = opts.data.get("control_net_max_models_num", 1)
  91. arg_num = 3
  92. item_list = []
  93. video_list = []
  94. for input_set in [tuple(args[:contents_num * arg_num][i:i+3]) for i in range(0, len(args[:contents_num * arg_num]), arg_num)]:
  95. if input_set[0] is not None:
  96. item_list.append([get_all_frames(input_set[0]), "video"])
  97. video_list.append(get_all_frames(input_set[0]))
  98. if input_set[1] is not None:
  99. item_list.append([cv2.cvtColor(pil2cv(input_set[1]["image"]), cv2.COLOR_BGRA2RGB), "image"])
  100. save_pre = list(args[2:contents_num * arg_num:3])
  101. item_num = len(item_list)
  102. video_num = len(video_list)
  103. duration, = args[contents_num * arg_num:]
  104. frame_num = get_min_frame_num(video_list)
  105. if frame_num > 0:
  106. output_image_list = []
  107. pre_output_image_list = []
  108. for i in range(item_num):
  109. pre_output_image_list.append([])
  110. for frame in range(frame_num):
  111. copy_p = copy.copy(p)
  112. copy_p.control_net_input_image = []
  113. for item in item_list:
  114. if item[1] == "video":
  115. copy_p.control_net_input_image.append(item[0][frame])
  116. elif item[1] == "image":
  117. copy_p.control_net_input_image.append(item[0])
  118. else:
  119. continue
  120. proc = process_images(copy_p)
  121. img = proc.images[0]
  122. output_image_list.append(img)
  123. for i in range(len(save_pre)):
  124. if save_pre[i]:
  125. try:
  126. pre_output_image_list[i].append(proc.images[i + 1])
  127. except:
  128. print(f"proc.images[{i} failed")
  129. copy_p.close()
  130. # filename format is seq-seed-animation.gif seq is 5 places left filled with 0
  131. seq = images.get_next_sequence_number(f"{p.outpath_samples}{_BASEDIR}", "")
  132. filename = f"{seq:05}-{proc.seed}-{_BASEFILE}"
  133. save_gif(p.outpath_samples, output_image_list, filename, duration)
  134. proc.images = [f"{p.outpath_samples}{_BASEDIR}/{filename}.gif"]
  135. for i in range(len(save_pre)):
  136. if save_pre[i]:
  137. # control files add -controlX.gif where X is the controlnet number
  138. save_gif(p.outpath_samples, pre_output_image_list[i], f"{filename}-control{i}", duration)
  139. proc.images.append(f"{p.outpath_samples}{_BASEDIR}/{filename}-control{i}.gif")
  140. else:
  141. proc = process_images(p)
  142. return proc