grenerate_main_image_test.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import os
  2. import copy
  3. import time
  4. from .image_deal_base_func import *
  5. from PIL import Image, ImageDraw
  6. from blend_modes import multiply
  7. import os
  8. import settings
  9. from functools import wraps
  10. def time_it(func):
  11. @wraps(func) # 使用wraps来保留原始函数的元数据信息
  12. def wrapper(*args, **kwargs):
  13. start_time = time.time() # 记录开始时间
  14. result = func(*args, **kwargs) # 调用原始函数
  15. end_time = time.time() # 记录结束时间
  16. print(f"Executing {func.__name__} took {end_time - start_time:.4f} seconds.") # 打印耗时
  17. return result
  18. return wrapper
  19. class GeneratePic(object):
  20. def __init__(self, is_test=False):
  21. # self.logger = MyLogger()
  22. self.is_test = is_test
  23. pass
  24. @time_it
  25. def get_mask_and_config(self, im_jpg: Image, im_png: Image):
  26. """
  27. 步骤:
  28. 1、尺寸进行对应缩小
  29. 2、查找并设定鞋底阴影蒙版
  30. 3、自动色阶检查亮度
  31. 4、输出自动色阶参数、以及放大的尺寸蒙版
  32. """
  33. # ===================尺寸进行对应缩小(提升处理速度)
  34. im_jpg = to_resize(im_jpg, width=800)
  35. im_png = to_resize(im_png, width=800)
  36. x1, y1, x2, y2 = im_png.getbbox()
  37. cv2_png = pil_to_cv2(im_png)
  38. # =====================设定鞋底阴影图的蒙版
  39. # 查找每列的最低非透明点
  40. min_y_values = find_lowest_non_transparent_points(cv2_png)
  41. # 在鞋底最低处增加一条直线蒙版,蒙版宽度为有效区域大小
  42. image_high = im_jpg.height
  43. print("图片高度:", image_high)
  44. cv2_jpg = pil_to_cv2(im_jpg)
  45. # 返回线条图片,以及最低位置
  46. img_with_shifted_line, lowest_y = draw_shifted_line(image=cv2_jpg,
  47. min_y_values=min_y_values,
  48. shift_amount=15,
  49. one_line_pos=(x1, x2),
  50. line_color=(0, 0, 0),
  51. line_thickness=20)
  52. # 制作蒙版
  53. mask_line = cv2_to_pil(img_with_shifted_line)
  54. mask = mask_line.convert('L') # 转换为灰度图
  55. mask = ImageOps.invert(mask)
  56. # 蒙版扩边
  57. mask = expand_mask(mask, expansion_radius=30, blur_radius=10)
  58. # ====================生成新的图片
  59. bg = Image.new(mode="RGBA", size=im_png.size, color=(255, 255, 255, 255))
  60. bg.paste(im_png, mask=im_png)
  61. bg.paste(im_jpg, mask=mask) # 粘贴有阴影的地方
  62. if self.is_test:
  63. _bg = bg.copy()
  64. draw = ImageDraw.Draw(_bg)
  65. # 定义直线的起点和终点坐标
  66. start_point = (0, lowest_y) # 直线的起始点
  67. end_point = (_bg.width, lowest_y) # 直线的结束点
  68. # 定义直线的颜色(R, G, B)
  69. line_color = (255, 0, 0) # 红色
  70. # 绘制直线
  71. draw.line([start_point, end_point], fill=line_color, width=1)
  72. # mask.show()
  73. # bg = pil_to_cv2(bg)
  74. # cv2.line(bg, (x1, lowest_y + 5), (x2, lowest_y + 5), color=(0, 0, 0),thickness=2)
  75. # bg = cv2_to_pil(bg)
  76. _r = Image.new(mode="RGBA", size=im_png.size, color=(246, 147, 100, 255))
  77. mask_line = mask_line.convert('L') # 转换为灰度图
  78. mask_line = ImageOps.invert(mask_line)
  79. _bg.paste(_r, mask=mask)
  80. _bg.show()
  81. # bg.save(r"C:\Users\gymmc\Desktop\data\bg.png")
  82. # bg.show()
  83. # ==================自动色阶处理======================
  84. # 对上述拼接后的图片进行自动色阶处理
  85. bg = bg.convert("RGB")
  86. _im = cv2.cvtColor(np.asarray(bg), cv2.COLOR_RGB2BGR)
  87. # 背景阴影
  88. im_shadow = cv2.cvtColor(_im, cv2.COLOR_BGR2GRAY)
  89. print("image_high lowest_y", image_high, lowest_y)
  90. if lowest_y < 0 or lowest_y >= image_high:
  91. lowest_y = image_high - 1
  92. print("image_high lowest_y", image_high, lowest_y)
  93. rows = [lowest_y] # 需要检查的像素行
  94. _im_shadow = copy.copy(im_shadow)
  95. Midtones = 0.7
  96. Highlight = 235
  97. k = 8
  98. while k:
  99. k -= 1
  100. Midtones += 0.1
  101. if Midtones > 1:
  102. Midtones = 1
  103. Highlight -= 3
  104. _im_shadow = levels_adjust(img=im_shadow, Shadow=0, Midtones=Midtones, Highlight=Highlight,
  105. OutShadow=0,
  106. OutHighlight=255, Dim=3)
  107. brightness_list = calculate_average_brightness_opencv(img_gray=_im_shadow, rows_to_check=rows)
  108. print(brightness_list)
  109. if brightness_list[0] >= settings.GRENERATE_MAIN_PIC_BRIGHTNESS:
  110. break
  111. print("Midtones,Highlight:", Midtones, Highlight)
  112. im_shadow = cv2_to_pil(_im_shadow)
  113. # ========================================================
  114. # 计算阴影的亮度,用于确保阴影不要太黑
  115. # 1、图片预处理,只保留阴影
  116. only_shadow_img = im_shadow.copy()
  117. only_shadow_img.paste(Image.new(mode="RGBA", size=only_shadow_img.size, color=(255, 255, 255, 255)),
  118. mask=im_png)
  119. average_brightness = calculated_shadow_brightness(only_shadow_img)
  120. print("average_brightness:", average_brightness)
  121. config = {
  122. "Midtones": Midtones,
  123. "Highlight": Highlight,
  124. "average_brightness": average_brightness,
  125. }
  126. return mask, config
  127. def get_mask_and_config_beifen(self, im_jpg: Image, im_png: Image, out_image_path=None):
  128. """
  129. 步骤:
  130. 1、尺寸进行对应缩小
  131. 2、查找并设定鞋底阴影蒙版
  132. 3、自动色阶检查亮度
  133. 4、输出自动色阶参数、以及放大的尺寸蒙版
  134. """
  135. # ===================尺寸进行对应缩小
  136. orign_x, orign_y = im_jpg.size
  137. im_jpg = to_resize(im_jpg, width=800)
  138. im_png = to_resize(im_png, width=800)
  139. x1, y1, x2, y2 = im_png.getbbox()
  140. cv2_png = pil_to_cv2(im_png)
  141. # =====================设定鞋底阴影图的蒙版
  142. # 查找每列的最低非透明点
  143. min_y_values = find_lowest_non_transparent_points(cv2_png)
  144. # 在鞋底最低处增加一条直线蒙版,蒙版宽度为有效区域大小
  145. cv2_jpg = pil_to_cv2(im_jpg)
  146. # 返回线条图片,以及最低位置
  147. img_with_shifted_line, lowest_y = draw_shifted_line(image=cv2_jpg,
  148. min_y_values=min_y_values,
  149. shift_amount=15,
  150. one_line_pos=(x1, x2),
  151. line_color=(0, 0, 0),
  152. line_thickness=20)
  153. # 制作蒙版
  154. mask = cv2_to_pil(img_with_shifted_line)
  155. mask = mask.convert('L') # 转换为灰度图
  156. mask = ImageOps.invert(mask)
  157. # 蒙版扩边
  158. mask = expand_mask(mask, expansion_radius=30, blur_radius=10)
  159. # ====================生成新的图片
  160. bg = Image.new(mode="RGBA", size=im_png.size, color=(255, 255, 255, 255))
  161. bg.paste(im_png, mask=im_png)
  162. bg.paste(im_jpg, mask=mask) # 粘贴有阴影的地方
  163. # bg = pil_to_cv2(bg)
  164. # cv2.line(bg, (x1, lowest_y + 5), (x2, lowest_y + 5), color=(0, 0, 0),thickness=2)
  165. # bg = cv2_to_pil(bg)
  166. # bg.show()
  167. # bg.save(r"C:\Users\gymmc\Desktop\data\bg.png")
  168. # bg.show()
  169. # ==================自动色阶处理======================
  170. # 对上述拼接后的图片进行自动色阶处理
  171. bg = bg.convert("RGB")
  172. _im = cv2.cvtColor(np.asarray(bg), cv2.COLOR_RGB2BGR)
  173. # 背景阴影
  174. im_shadow = cv2.cvtColor(_im, cv2.COLOR_BGR2GRAY)
  175. rows = [lowest_y] # 需要检查的像素行
  176. _im_shadow = copy.copy(im_shadow)
  177. Midtones = 0.62
  178. Highlight = 235
  179. k = 10
  180. while k:
  181. k -= 1
  182. Midtones += 0.1
  183. if Midtones > 1:
  184. Midtones = 1
  185. Highlight -= 3
  186. _im_shadow = levels_adjust(img=im_shadow, Shadow=0, Midtones=Midtones, Highlight=Highlight,
  187. OutShadow=0,
  188. OutHighlight=255, Dim=3)
  189. brightness_list = calculate_average_brightness_opencv(img_gray=_im_shadow, rows_to_check=rows)
  190. print(brightness_list)
  191. if brightness_list[0] >= 254:
  192. break
  193. print("Midtones,Highlight:", Midtones, Highlight)
  194. config = (Midtones, Highlight)
  195. im_shadow = cv2_to_pil(_im_shadow)
  196. im_shadow.paste(im_png, (0, 0), im_png) # 把原图粘贴回去,避免色差
  197. if out_image_path:
  198. im_shadow.save(out_image_path)
  199. return mask, config
  200. def my_test(self,**kwargs):
  201. if "output_queue" in kwargs:
  202. output_queue = kwargs["output_queue"]
  203. else:
  204. output_queue = None
  205. time.sleep(3)
  206. if output_queue is not None:
  207. output_queue.put(True)
  208. @time_it
  209. def run(self, image_path, cut_image_path, out_path, image_deal_mode=0, image_index=99,
  210. out_pic_size=1024, is_logo=True, out_process_path_1=None, out_process_path_2=None,
  211. resize_mode=None, max_box=None, logo_path="", **kwargs): # im 为cv对象
  212. """
  213. image_path:原始图
  214. cut_image_path:抠图结果 与原始图尺寸相同
  215. out_path:输出主图路径
  216. image_deal_mode:图片处理模式,1表示需要镜像处理
  217. image_index:图片顺序索引
  218. out_pic_size:输出图片宽度大小
  219. is_logo=True 是否要添加logo水印
  220. out_process_path_1=None, 有阴影的图片,白底非透明
  221. out_process_path_2=None, 已抠图的图片
  222. resize_mode=0,1,2 主体缩小尺寸
  223. """
  224. if "output_queue" in kwargs:
  225. output_queue = kwargs["output_queue"]
  226. else:
  227. output_queue = None
  228. # ==========先进行剪切原图
  229. _s = time.time()
  230. orign_im = Image.open(image_path) # 原始图
  231. print("242 need_time_1:{}".format(time.time() - _s))
  232. orign_x, orign_y = orign_im.size
  233. cut_image = Image.open(cut_image_path) # 原始图的已扣图
  234. cut_image, new_box = get_mini_crop_img(img=cut_image)
  235. im_shadow = orign_im.crop(new_box) # 切图
  236. new_x, new_y = im_shadow.size
  237. # ================自动色阶处理
  238. _s = time.time()
  239. shadow_mask, config = self.get_mask_and_config(im_jpg=im_shadow, im_png=cut_image)
  240. print("242 need_time_2:{}".format(time.time() - _s))
  241. shadow_mask = shadow_mask.resize(im_shadow.size)
  242. # =====抠图,形成新的阴影背景图=====
  243. _new_im_shadow = Image.new(mode="RGBA", size=im_shadow.size, color=(255, 255, 255, 255))
  244. _new_im_shadow.paste(im_shadow, mask=shadow_mask) # 粘贴有阴影的地方
  245. # _new_im_shadow.show()
  246. _new_im_shadow = pil_to_cv2(_new_im_shadow)
  247. _new_im_shadow = cv2.cvtColor(_new_im_shadow, cv2.COLOR_BGR2GRAY)
  248. _new_im_shadow = levels_adjust(img=_new_im_shadow,
  249. Shadow=0,
  250. Midtones=config["Midtones"],
  251. Highlight=config["Highlight"],
  252. OutShadow=0,
  253. OutHighlight=255, Dim=3)
  254. im_shadow = cv2_to_pil(_new_im_shadow)
  255. # ================处理阴影的亮度==================
  256. average_brightness = config["average_brightness"]
  257. if config["average_brightness"] < 180:
  258. # 调整阴影亮度
  259. backdrop_prepped = np.asfarray(Image.new(mode="RGBA", size=im_shadow.size, color=(255, 255, 255, 255)))
  260. im_shadow = im_shadow.convert("RGBA")
  261. source_prepped = np.asfarray(im_shadow)
  262. # im_shadow.show()
  263. opacity = (average_brightness - 30) / 160
  264. opacity = max(0.5, min(opacity, 1))
  265. print("阴影透明度:{}%".format(int(opacity * 100)))
  266. blended_np = multiply(backdrop_prepped, source_prepped, opacity=int(opacity * 100) / 100)
  267. im_shadow = Image.fromarray(np.uint8(blended_np)).convert('RGB')
  268. # im_shadow.show()
  269. # 把原图粘贴回去,避免色差
  270. im_shadow.paste(cut_image, (0, 0), mask=cut_image)
  271. # _new_im_shadow.show()
  272. # ===========处理其他====================
  273. # 保存带有阴影的底图,没有logo
  274. if out_process_path_1:
  275. out_image_1 = im_shadow.copy()
  276. if image_deal_mode == 1:
  277. out_image_1 = out_image_1.transpose(Image.FLIP_LEFT_RIGHT)
  278. out_image_1.save(out_process_path_1)
  279. # 保存抠图结果,没有底图,没有logo
  280. if out_process_path_2:
  281. out_image_2 = cut_image.copy()
  282. if image_deal_mode == 1:
  283. out_image_2 = out_image_2.transpose(Image.FLIP_LEFT_RIGHT)
  284. out_image_2.save(out_process_path_2)
  285. # 不生成主图时直接退出
  286. if not out_path:
  287. return True
  288. # im_shadow.show()
  289. # =====================主图物体的缩放依据大小
  290. if max_box:
  291. im_shadow = to_resize(_im=im_shadow, width=max_box[0], high=max_box[1])
  292. cut_image = to_resize(_im=cut_image, width=max_box[0], high=max_box[1])
  293. else:
  294. if resize_mode is None:
  295. im_shadow = to_resize(_im=im_shadow, width=1400, high=1400)
  296. cut_image = to_resize(_im=cut_image, width=1400, high=1400)
  297. elif resize_mode == 1:
  298. im_shadow = to_resize(_im=im_shadow, width=1400, high=1400)
  299. cut_image = to_resize(_im=cut_image, width=1400, high=1400)
  300. elif resize_mode == 2:
  301. # todo 兼容长筒靴等,将图片大小限制在一个指定的box内
  302. im_shadow = to_resize(_im=im_shadow, width=650)
  303. cut_image = to_resize(_im=cut_image, width=650)
  304. # 再次检查需要约束缩小到一定高度,适应长筒靴
  305. _im_x, _im_y = cut_image.size
  306. if _im_y > 1400:
  307. im_shadow = to_resize(_im=im_shadow, high=1400)
  308. cut_image = to_resize(_im=cut_image, high=1400)
  309. # if im_shadow.height <= im_shadow.width * 1.2:
  310. # im_shadow = to_resize(_im=im_shadow, width=650)
  311. # cut_image = to_resize(_im=cut_image, width=650)
  312. # else:
  313. # im_shadow = to_resize(_im=im_shadow, high=1400)
  314. # cut_image = to_resize(_im=cut_image, high=1400)
  315. if image_deal_mode == 1:
  316. # 翻转
  317. im_shadow = im_shadow.transpose(Image.FLIP_LEFT_RIGHT)
  318. cut_image = cut_image.transpose(Image.FLIP_LEFT_RIGHT)
  319. # 创建底层背景
  320. image_bg = Image.new("RGB", (1600, 1600), (255, 255, 255))
  321. image_bg_x, image_bg_y = image_bg.size
  322. image_x, image_y = im_shadow.size
  323. _x = int((image_bg_x - image_x) / 2)
  324. _y = int((image_bg_y - image_y) / 2)
  325. image_bg.paste(im_shadow, (_x, _y))
  326. image_bg.paste(cut_image, (_x, _y), cut_image) # 再叠加原图避免色差
  327. if "小苏" in settings.Company:
  328. # 所有主图加logo
  329. is_logo = True
  330. if is_logo:
  331. # logo_path = ""
  332. # if settings.PROJECT == "红蜻蜓":
  333. # logo_path = r"resources\LOGO\HQT\logo.png"
  334. # elif settings.PROJECT == "惠利玛":
  335. # if "小苏" in settings.Company:
  336. # logo_path = r"resources\LOGO\xiaosushuoxie\logo.png"
  337. # elif "惠利玛" in settings.Company:
  338. # logo_path = r"resources\LOGO\HLM\logo.png"
  339. # else:
  340. # pass
  341. if not logo_path:
  342. logo_im = Image.new("RGBA", (1600, 1600), (0, 0, 0, 0))
  343. else:
  344. if os.path.exists(logo_path):
  345. logo_im = Image.open(logo_path)
  346. else:
  347. logo_im = Image.new("RGBA", (1600, 1600), (0, 0, 0, 0))
  348. image_bg.paste(logo_im, (0, 0), logo_im)
  349. # image_bg = image_bg.resize((out_pic_size, out_pic_size), Image.BICUBIC)
  350. if settings.OUT_PIC_FACTOR > 1.0:
  351. print("图片锐化处理")
  352. image_bg = sharpen_image(image_bg, factor=settings.OUT_PIC_FACTOR)
  353. if out_pic_size < 1600:
  354. image_bg = image_bg.resize((out_pic_size, out_pic_size), resample=settings.RESIZE_IMAGE_MODE)
  355. if settings.OUT_PIC_MODE == ".jpg":
  356. image_bg.save(out_path, quality=100, dpi=(300, 300), format="JPEG")
  357. else:
  358. # quality=quality
  359. image_bg.save(out_path, quality=100)
  360. if output_queue is not None:
  361. output_queue.put(True)
  362. return True