grenerate_main_image_test.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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. from .multi_threaded_image_saving import ImageSaver
  11. from .get_mask_by_green import GetMask
  12. from middleware import UnicornException
  13. def time_it(func):
  14. @wraps(func) # 使用wraps来保留原始函数的元数据信息
  15. def wrapper(*args, **kwargs):
  16. start_time = time.time() # 记录开始时间
  17. result = func(*args, **kwargs) # 调用原始函数
  18. end_time = time.time() # 记录结束时间
  19. print(
  20. f"Executing {func.__name__} took {end_time - start_time:.4f} seconds."
  21. ) # 打印耗时
  22. return result
  23. return wrapper
  24. class GeneratePic(object):
  25. def __init__(self, is_test=False):
  26. # self.logger = MyLogger()
  27. self.is_test = is_test
  28. self.saver = ImageSaver()
  29. pass
  30. @time_it
  31. def get_mask_and_config(self, im_jpg: Image, im_png: Image, curve_mask: bool):
  32. """
  33. 步骤:
  34. 1、尺寸进行对应缩小
  35. 2、查找并设定鞋底阴影蒙版
  36. 3、自动色阶检查亮度
  37. 4、输出自动色阶参数、以及放大的尺寸蒙版
  38. """
  39. # ===================尺寸进行对应缩小(提升处理速度)
  40. im_jpg = to_resize(im_jpg, width=800)
  41. im_png = to_resize(im_png, width=800)
  42. x1, y1, x2, y2 = im_png.getbbox()
  43. cv2_png = pil_to_cv2(im_png)
  44. # =====================设定鞋底阴影图的蒙版
  45. # 查找每列的最低非透明点
  46. min_y_values = find_lowest_non_transparent_points(cv2_png)
  47. # 在鞋底最低处增加一条直线蒙版,蒙版宽度为有效区域大小
  48. image_high = im_jpg.height
  49. print("图片高度:", image_high)
  50. cv2_jpg = pil_to_cv2(im_jpg)
  51. # 返回线条图片,以及最低位置
  52. print("返回线条图片,以及最低位置")
  53. # crop_image_box=(x1, y1, x2, y2),
  54. if curve_mask:
  55. crop_image_box = None
  56. else:
  57. # 不需要曲线部分的蒙版
  58. crop_image_box = (x1, y1, x2, y2)
  59. img_with_shifted_line, lowest_y = draw_shifted_line(
  60. image=cv2_jpg,
  61. min_y_values=min_y_values,
  62. shift_amount=15,
  63. one_line_pos=(x1, x2),
  64. line_color=(0, 0, 0),
  65. line_thickness=20,
  66. app=None,
  67. crop_image_box=crop_image_box,
  68. )
  69. print("66 制作蒙版")
  70. # 制作蒙版
  71. mask_line = cv2_to_pil(img_with_shifted_line)
  72. mask = mask_line.convert("L") # 转换为灰度图
  73. mask = ImageOps.invert(mask)
  74. # 蒙版扩边
  75. print("72 蒙版扩边")
  76. # 默认expansion_radius 65 blur_radius 45
  77. mask = expand_or_shrink_mask(
  78. pil_image=mask, expansion_radius=50, blur_radius=35
  79. )
  80. # =============使用绿色蒙版进行处理
  81. if settings.IS_GET_GREEN_MASK:
  82. print("============使用绿色蒙版进行处理")
  83. mask = mask.convert("RGB")
  84. white_bg = Image.new(mode="RGB", size=im_png.size, color=(0, 0, 0))
  85. green_areas_mask_pil = GetMask().find_green_areas(cv2_jpg)
  86. green_areas_mask_pil = expand_or_shrink_mask(
  87. pil_image=green_areas_mask_pil, expansion_radius=15, blur_radius=5
  88. )
  89. mask.paste(white_bg, mask=green_areas_mask_pil.convert("L"))
  90. mask = mask.convert("L")
  91. # ====================生成新的图片
  92. print("84 生成新的图片")
  93. bg = Image.new(mode="RGBA", size=im_png.size, color=(255, 255, 255, 255))
  94. bg.paste(im_png, mask=im_png)
  95. bg.paste(im_jpg, mask=mask) # 粘贴有阴影的地方
  96. if image_high > y2 + 20:
  97. lowest_y = y2 + 20
  98. if self.is_test:
  99. _bg = bg.copy()
  100. draw = ImageDraw.Draw(_bg)
  101. # 定义直线的起点和终点坐标
  102. start_point = (0, lowest_y) # 直线的起始点
  103. end_point = (_bg.width, lowest_y) # 直线的结束点
  104. # 定义直线的颜色(R, G, B)
  105. line_color = (255, 0, 0) # 红色
  106. _r = Image.new(mode="RGBA", size=im_png.size, color=(246, 147, 100, 255))
  107. # mask_line = mask_line.convert('L') # 转换为灰度图
  108. # mask_line = ImageOps.invert(mask_line)
  109. # _bg.paste(_r, mask=mask)
  110. # 绘制直线
  111. draw.line([start_point, end_point], fill=line_color, width=1)
  112. _bg.show()
  113. # bg.save(r"C:\Users\gymmc\Desktop\data\bg.png")
  114. # bg.show()
  115. # ==================自动色阶处理======================
  116. # 对上述拼接后的图片进行自动色阶处理
  117. bg = bg.convert("RGB")
  118. _im = cv2.cvtColor(np.asarray(bg), cv2.COLOR_RGB2BGR)
  119. # 背景阴影
  120. im_shadow = cv2.cvtColor(_im, cv2.COLOR_BGR2GRAY)
  121. print("image_high lowest_y", image_high, lowest_y)
  122. if lowest_y < 0 or lowest_y >= image_high:
  123. lowest_y = image_high - 1
  124. print("image_high lowest_y", image_high, lowest_y)
  125. rows = [lowest_y] # 需要检查的像素行
  126. print("copy.copy(im_shadow)")
  127. _im_shadow = copy.copy(im_shadow)
  128. Midtones = 0.7
  129. Highlight = 235
  130. k = copy.copy(settings.COLOR_GRADATION_CYCLES)
  131. print("循环识别")
  132. xunhuan = 0
  133. while k:
  134. xunhuan += 1
  135. # if settings.app:
  136. # settings.app.processEvents()
  137. k -= 1
  138. Midtones += 0.035
  139. if Midtones > 1.7:
  140. Midtones = 1.7
  141. Highlight -= 3
  142. _im_shadow = levels_adjust(
  143. img=im_shadow,
  144. Shadow=0,
  145. Midtones=Midtones,
  146. Highlight=Highlight,
  147. OutShadow=0,
  148. OutHighlight=255,
  149. Dim=3,
  150. )
  151. brightness_list = calculate_average_brightness_opencv(
  152. img_gray=_im_shadow, rows_to_check=rows
  153. )
  154. print(
  155. "循环识别:{},Midtones:{},Highlight:{},brightness_list:{}".format(
  156. xunhuan, Midtones, Highlight, brightness_list
  157. )
  158. )
  159. if brightness_list[0] >= settings.GRENERATE_MAIN_PIC_BRIGHTNESS:
  160. break
  161. im_shadow = cv2_to_pil(_im_shadow)
  162. # ========================================================
  163. # 计算阴影的亮度,用于确保阴影不要太黑
  164. # 1、图片预处理,只保留阴影
  165. only_shadow_img = im_shadow.copy()
  166. only_shadow_img.paste(
  167. Image.new(
  168. mode="RGBA", size=only_shadow_img.size, color=(255, 255, 255, 255)
  169. ),
  170. mask=im_png,
  171. )
  172. average_brightness = calculated_shadow_brightness(only_shadow_img)
  173. print("average_brightness:", average_brightness)
  174. config = {
  175. "Midtones": Midtones,
  176. "Highlight": Highlight,
  177. "average_brightness": average_brightness,
  178. }
  179. return mask, config
  180. def get_mask_and_config_1_2025_05_18(self, im_jpg: Image, im_png: Image):
  181. """
  182. 步骤:
  183. 1、尺寸进行对应缩小
  184. 2、查找并设定鞋底阴影蒙版
  185. 3、自动色阶检查亮度
  186. 4、输出自动色阶参数、以及放大的尺寸蒙版
  187. """
  188. # ===================尺寸进行对应缩小(提升处理速度)
  189. im_jpg = to_resize(im_jpg, width=800)
  190. im_png = to_resize(im_png, width=800)
  191. x1, y1, x2, y2 = im_png.getbbox()
  192. cv2_png = pil_to_cv2(im_png)
  193. # =====================设定鞋底阴影图的蒙版
  194. # 查找每列的最低非透明点
  195. min_y_values = find_lowest_non_transparent_points(cv2_png)
  196. # 在鞋底最低处增加一条直线蒙版,蒙版宽度为有效区域大小
  197. image_high = im_jpg.height
  198. print("图片高度:", image_high)
  199. cv2_jpg = pil_to_cv2(im_jpg)
  200. # 返回线条图片,以及最低位置
  201. print("返回线条图片,以及最低位置")
  202. img_with_shifted_line, lowest_y = draw_shifted_line(
  203. image=cv2_jpg,
  204. min_y_values=min_y_values,
  205. shift_amount=15,
  206. one_line_pos=(x1, x2),
  207. line_color=(0, 0, 0),
  208. line_thickness=20,
  209. app=None,
  210. crop_image_box=(x1, y1, x2, y2),
  211. )
  212. print("66 制作蒙版")
  213. # 制作蒙版
  214. mask_line = cv2_to_pil(img_with_shifted_line)
  215. mask = mask_line.convert("L") # 转换为灰度图
  216. mask = ImageOps.invert(mask)
  217. # 蒙版扩边
  218. print("72 蒙版扩边")
  219. # 默认expansion_radius 65 blur_radius 45
  220. mask = expand_or_shrink_mask(
  221. pil_image=mask, expansion_radius=50, blur_radius=35
  222. )
  223. # mask1 = expand_mask(mask, expansion_radius=30, blur_radius=10)
  224. # mask1.save("mask1.png")
  225. # mask2 = expand_or_shrink_mask(pil_image=mask, expansion_radius=60, blur_radius=30)
  226. # mask2.save("mask2.png")
  227. # raise 11
  228. # ====================生成新的图片
  229. print("84 生成新的图片")
  230. bg = Image.new(mode="RGBA", size=im_png.size, color=(255, 255, 255, 255))
  231. bg.paste(im_png, mask=im_png)
  232. bg.paste(im_jpg, mask=mask) # 粘贴有阴影的地方
  233. if self.is_test:
  234. _bg = bg.copy()
  235. draw = ImageDraw.Draw(_bg)
  236. # 定义直线的起点和终点坐标
  237. start_point = (0, lowest_y) # 直线的起始点
  238. end_point = (_bg.width, lowest_y) # 直线的结束点
  239. # 定义直线的颜色(R, G, B)
  240. line_color = (255, 0, 0) # 红色
  241. # 绘制直线
  242. draw.line([start_point, end_point], fill=line_color, width=1)
  243. # mask.show()
  244. # bg = pil_to_cv2(bg)
  245. # cv2.line(bg, (x1, lowest_y + 5), (x2, lowest_y + 5), color=(0, 0, 0),thickness=2)
  246. # bg = cv2_to_pil(bg)
  247. _r = Image.new(mode="RGBA", size=im_png.size, color=(246, 147, 100, 255))
  248. mask_line = mask_line.convert("L") # 转换为灰度图
  249. mask_line = ImageOps.invert(mask_line)
  250. _bg.paste(_r, mask=mask)
  251. _bg.show()
  252. # bg.save(r"C:\Users\gymmc\Desktop\data\bg.png")
  253. # bg.show()
  254. # ==================自动色阶处理======================
  255. # 对上述拼接后的图片进行自动色阶处理
  256. bg = bg.convert("RGB")
  257. _im = cv2.cvtColor(np.asarray(bg), cv2.COLOR_RGB2BGR)
  258. # 背景阴影
  259. im_shadow = cv2.cvtColor(_im, cv2.COLOR_BGR2GRAY)
  260. print("image_high lowest_y", image_high, lowest_y)
  261. if lowest_y < 0 or lowest_y >= image_high:
  262. lowest_y = image_high - 1
  263. print("image_high lowest_y", image_high, lowest_y)
  264. rows = [lowest_y] # 需要检查的像素行
  265. print("copy.copy(im_shadow)")
  266. _im_shadow = copy.copy(im_shadow)
  267. Midtones = 0.7
  268. Highlight = 235
  269. k = 12
  270. print("循环识别")
  271. while k:
  272. print("循环识别:{}".format(k))
  273. # if settings.app:
  274. # settings.app.processEvents()
  275. k -= 1
  276. Midtones += 0.1
  277. if Midtones > 1:
  278. Midtones = 1
  279. Highlight -= 3
  280. _im_shadow = levels_adjust(
  281. img=im_shadow,
  282. Shadow=0,
  283. Midtones=Midtones,
  284. Highlight=Highlight,
  285. OutShadow=0,
  286. OutHighlight=255,
  287. Dim=3,
  288. )
  289. brightness_list = calculate_average_brightness_opencv(
  290. img_gray=_im_shadow, rows_to_check=rows
  291. )
  292. print(brightness_list)
  293. if brightness_list[0] >= settings.GRENERATE_MAIN_PIC_BRIGHTNESS:
  294. break
  295. print("Midtones,Highlight:", Midtones, Highlight)
  296. im_shadow = cv2_to_pil(_im_shadow)
  297. # ========================================================
  298. # 计算阴影的亮度,用于确保阴影不要太黑
  299. # 1、图片预处理,只保留阴影
  300. only_shadow_img = im_shadow.copy()
  301. only_shadow_img.paste(
  302. Image.new(
  303. mode="RGBA", size=only_shadow_img.size, color=(255, 255, 255, 255)
  304. ),
  305. mask=im_png,
  306. )
  307. average_brightness = calculated_shadow_brightness(only_shadow_img)
  308. print("average_brightness:", average_brightness)
  309. config = {
  310. "Midtones": Midtones,
  311. "Highlight": Highlight,
  312. "average_brightness": average_brightness,
  313. }
  314. return mask, config
  315. def my_test(self, **kwargs):
  316. if "output_queue" in kwargs:
  317. output_queue = kwargs["output_queue"]
  318. else:
  319. output_queue = None
  320. time.sleep(3)
  321. if output_queue is not None:
  322. output_queue.put(True)
  323. def paste_img(self,image, top_img, base="nw", value=(0, 0), ):
  324. """
  325. {
  326. "command": "paste_img",
  327. "im": 需要粘贴的图片
  328. "pos": {"plugins_mode": "relative", # pixel
  329. "base": "center", # nw,nc,ne,ec ... 各个方向参考点
  330. "value": (100, 100),
  331. "percentage": (0.5, 0.5),
  332. },
  333. "margins": (0, 0, 0, 0), # 上下左右边距
  334. }
  335. """
  336. value = (int(value[0]), int(value[1]))
  337. # 处理默认值
  338. base = "nw" if not base else base
  339. top, down, left, right = 0, 0, 0, 0
  340. # 基于右边,上下居中
  341. if base == "ec" or base == "ce":
  342. p_x = int(image.width - (top_img.width + value[0]))
  343. p_y = int((image.height - top_img.height) / 2) + value[1]
  344. # 基于顶部,左右居中
  345. if base == "nc" or base == "cn":
  346. # 顶部对齐
  347. deviation_x, deviation_y = int((image.width - top_img.width) / 2), int(
  348. (image.height - top_img.height) / 2
  349. )
  350. p_x = deviation_x + value[0] + left
  351. p_y = value[1]
  352. # 基于右上角
  353. if base == "en" or base == "ne":
  354. p_x = int(image.width - (top_img.width + value[0])) + left
  355. p_y = value[1]
  356. # 基于左上角
  357. if base == "nw" or base == "wn":
  358. deviation_x, deviation_y = 0, 0
  359. p_x, p_y = value
  360. # 基于底部,左右居中
  361. if base == "cs" or base == "sc":
  362. deviation_x, deviation_y = int((image.width - top_img.width) / 2), int(
  363. (image.height - top_img.height) / 2
  364. )
  365. p_y = image.height - (top_img.height + value[1] + down)
  366. p_x = deviation_x + value[0] + left
  367. # 上下左右居中
  368. if base == "center" or base == "cc":
  369. deviation_x, deviation_y = int((image.width - top_img.width) / 2), int(
  370. (image.height - top_img.height) / 2
  371. )
  372. p_x = deviation_x + value[0] + left
  373. p_y = deviation_y + value[1] + top
  374. # 基于左下角
  375. if base == "sw" or base == "ws":
  376. # deviation_x, deviation_y = 0, int((img.height - img_1.height))
  377. p_x = value[0] + left
  378. p_y = image.height - (top_img.height + value[1] + down)
  379. # 基于左边,上下居中
  380. if base == "wc" or base == "cw":
  381. p_x = value[0] + left
  382. p_y = int((image.height - top_img.height) / 2) + value[1] + top
  383. # 基于右下角
  384. if base == "es" or base == "se":
  385. p_x = int(image.width - (top_img.width + value[0])) + left
  386. p_y = image.height - (top_img.height + value[1] + down) + top
  387. try:
  388. image.paste(top_img, box=(p_x, p_y), mask=top_img)
  389. except:
  390. image.paste(top_img, box=(p_x, p_y), mask=top_img.convert("RGBA"))
  391. return image
  392. @time_it
  393. def run(
  394. self,
  395. image_path,
  396. cut_image_path,
  397. out_path,
  398. image_deal_mode=0,
  399. image_index=99,
  400. out_pic_size=1024,
  401. is_logo=True,
  402. out_process_path_1=None,
  403. out_process_path_2=None,
  404. resize_mode=None,
  405. max_box=None,
  406. logo_path="",
  407. curve_mask=False,
  408. **kwargs,
  409. ): # im 为cv对象
  410. """
  411. image_path:原始图
  412. cut_image_path:抠图结果 与原始图尺寸相同
  413. out_path:输出主图路径
  414. image_deal_mode:图片处理模式,1表示需要镜像处理
  415. image_index:图片顺序索引
  416. out_pic_size:输出图片宽度大小
  417. is_logo=True 是否要添加logo水印
  418. out_process_path_1=None, 有阴影的图片,白底非透明
  419. out_process_path_2=None, 已抠图的图片
  420. resize_mode=0,1,2 主体缩小尺寸
  421. curve_mask 为True时,表示为对鞋曲线部分的mask,不做剪裁
  422. """
  423. if "output_queue" in kwargs:
  424. output_queue = kwargs["output_queue"]
  425. else:
  426. output_queue = None
  427. # image_deal_mode = 0#不翻转图像
  428. padding_800image = settings.getSysConfigs(
  429. "basic_configs", "padding_800image", 100
  430. )
  431. # ==========先进行剪切原图
  432. _s = time.time()
  433. orign_im = Image.open(image_path) # 原始图
  434. print("242 need_time_1:{}".format(time.time() - _s))
  435. orign_x, orign_y = orign_im.size
  436. cut_image = Image.open(cut_image_path) # 原始图的已扣图
  437. cut_image, new_box = get_mini_crop_img(img=cut_image)
  438. im_shadow = orign_im.crop(new_box) # 切图
  439. new_x, new_y = im_shadow.size
  440. # ================自动色阶处理
  441. _s = time.time()
  442. shadow_mask, config = self.get_mask_and_config(
  443. im_jpg=im_shadow, im_png=cut_image, curve_mask=curve_mask
  444. )
  445. print("242 need_time_2:{}".format(time.time() - _s))
  446. shadow_mask = shadow_mask.resize(im_shadow.size)
  447. # =====抠图,形成新的阴影背景图=====
  448. _new_im_shadow = Image.new(
  449. mode="RGBA", size=im_shadow.size, color=(255, 255, 255, 255)
  450. )
  451. _new_im_shadow.paste(im_shadow, mask=shadow_mask) # 粘贴有阴影的地方
  452. # _new_im_shadow.show()
  453. _new_im_shadow = pil_to_cv2(_new_im_shadow)
  454. _new_im_shadow = cv2.cvtColor(_new_im_shadow, cv2.COLOR_BGR2GRAY)
  455. _new_im_shadow = levels_adjust(
  456. img=_new_im_shadow,
  457. Shadow=0,
  458. Midtones=config["Midtones"],
  459. Highlight=config["Highlight"],
  460. OutShadow=0,
  461. OutHighlight=255,
  462. Dim=3,
  463. )
  464. im_shadow = cv2_to_pil(_new_im_shadow)
  465. # ================处理阴影的亮度==================
  466. average_brightness = config["average_brightness"]
  467. if config["average_brightness"] < 180:
  468. # 调整阴影亮度
  469. backdrop_prepped = np.asfarray(
  470. Image.new(mode="RGBA", size=im_shadow.size, color=(255, 255, 255, 255))
  471. )
  472. im_shadow = im_shadow.convert("RGBA")
  473. source_prepped = np.asfarray(im_shadow)
  474. # im_shadow.show()
  475. opacity = (average_brightness - 30) / 160
  476. opacity = max(0.5, min(opacity, 1))
  477. print("阴影透明度:{}%".format(int(opacity * 100)))
  478. blended_np = multiply(
  479. backdrop_prepped, source_prepped, opacity=int(opacity * 100) / 100
  480. )
  481. im_shadow = Image.fromarray(np.uint8(blended_np)).convert("RGB")
  482. # im_shadow.show()
  483. # 把原图粘贴回去,避免色差
  484. im_shadow.paste(cut_image, (0, 0), mask=cut_image)
  485. # _new_im_shadow.show()
  486. # ===========处理其他====================
  487. # 保存带有阴影的底图,没有logo
  488. if out_process_path_1:
  489. out_image_1 = im_shadow.copy()
  490. if image_deal_mode == 1:
  491. out_image_1 = out_image_1.transpose(Image.FLIP_LEFT_RIGHT)
  492. self.saver.save_image(
  493. image=out_image_1, file_path=out_process_path_1, save_mode="png"
  494. )
  495. # save_image_by_thread(image=out_image_1, out_path=out_process_path_1)
  496. # out_image_1.save(out_process_path_1)
  497. # 保存抠图结果,没有底图,没有logo
  498. if out_process_path_2:
  499. out_image_2 = cut_image.copy()
  500. if image_deal_mode == 1:
  501. out_image_2 = out_image_2.transpose(Image.FLIP_LEFT_RIGHT)
  502. self.saver.save_image(
  503. image=out_image_2, file_path=out_process_path_2, save_mode="png"
  504. )
  505. # save_image_by_thread(image=out_image_2, out_path=out_process_path_2, save_mode="png")
  506. # out_image_2.save(out_process_path_2)
  507. # 不生成主图时直接退出
  508. if not out_path:
  509. return True
  510. if image_deal_mode == 1:
  511. # 翻转
  512. im_shadow = im_shadow.transpose(Image.FLIP_LEFT_RIGHT)
  513. cut_image = cut_image.transpose(Image.FLIP_LEFT_RIGHT)
  514. image_margin = int(padding_800image)
  515. bg_size = (1600, 1600)
  516. _offset_x, _offset_y = 0, 0
  517. scale_rate = 1
  518. # im_shadow.show()
  519. # =====================主图物体的缩放依据大小
  520. if image_margin is not None:
  521. _bbox = cut_image.getbbox()
  522. _x, _y = _bbox[0], _bbox[1]
  523. _w, _h = _bbox[2] - _bbox[0], _bbox[3] - _bbox[1]
  524. # 中心偏移量
  525. offset_x, offset_y = _x - (cut_image.width - _w) / 2, _y - (cut_image.height - _h) / 2,
  526. # print("中心偏移量:", offset_x, offset_y)
  527. # 透明底最小矩形
  528. scale_rate = self.get_scale(base_by_box=(bg_size[0] - image_margin * 2, bg_size[1] - image_margin * 2), image_size=(_w, _h))
  529. # 计算缩放比例,以及顶点相对位置
  530. # print("缩放比例:", scale_rate)
  531. # 偏移量
  532. _offset_x, _offset_y = offset_x * scale_rate, offset_y * scale_rate
  533. # print("偏移量:", _offset_x, _offset_y)
  534. # 阴影图缩放尺寸
  535. cut_image = to_resize(_im=cut_image, width=cut_image.width * scale_rate)
  536. im_shadow = to_resize(_im=im_shadow, width=im_shadow.width * scale_rate)
  537. else:
  538. if max_box:
  539. im_shadow = to_resize(_im=im_shadow, width=max_box[0], high=max_box[1])
  540. cut_image = to_resize(_im=cut_image, width=max_box[0], high=max_box[1])
  541. else:
  542. size_defind = 1400
  543. if resize_mode is None:
  544. im_shadow = to_resize(_im=im_shadow, width=size_defind, high=size_defind)
  545. cut_image = to_resize(_im=cut_image, width=size_defind, high=size_defind)
  546. elif resize_mode == 1:
  547. im_shadow = to_resize(_im=im_shadow, width=size_defind, high=size_defind)
  548. cut_image = to_resize(_im=cut_image, width=size_defind, high=size_defind)
  549. elif resize_mode == 2:
  550. # todo 兼容长筒靴等,将图片大小限制在一个指定的box内
  551. im_shadow = to_resize(_im=im_shadow, width=650)
  552. cut_image = to_resize(_im=cut_image, width=650)
  553. # 再次检查需要约束缩小到一定高度,适应长筒靴
  554. _im_x, _im_y = cut_image.size
  555. if _im_y > 1400:
  556. im_shadow = to_resize(_im=im_shadow, high=1400)
  557. cut_image = to_resize(_im=cut_image, high=1400)
  558. # if im_shadow.height <= im_shadow.width * 1.2:
  559. # im_shadow = to_resize(_im=im_shadow, width=650)
  560. # cut_image = to_resize(_im=cut_image, width=650)
  561. # else:
  562. # im_shadow = to_resize(_im=im_shadow, high=1400)
  563. # cut_image = to_resize(_im=cut_image, high=1400)
  564. # 创建底层背景
  565. image_bg = Image.new("RGB", bg_size, (255, 255, 255))
  566. image_bg = self.paste_img(image=image_bg, top_img=im_shadow, base="cc", value=(_offset_x * -1, _offset_y * -1))
  567. image_bg = self.paste_img(image=image_bg, top_img=cut_image, base="cc", value=(_offset_x * -1, _offset_y * -1))
  568. image_bg_x, image_bg_y = image_bg.size
  569. image_x, image_y = im_shadow.size
  570. _x = int((image_bg_x - image_x) / 2)
  571. _y = int((image_bg_y - image_y) / 2)
  572. image_bg.paste(im_shadow, (_x, _y))
  573. image_bg.paste(cut_image, (_x, _y), cut_image) # 再叠加原图避免色差
  574. if "小苏" in settings.Company:
  575. # 所有主图加logo
  576. is_logo = True
  577. if is_logo:
  578. # logo_path = ""
  579. # if settings.PROJECT == "红蜻蜓":
  580. # logo_path = r"resources\LOGO\HQT\logo.png"
  581. # elif settings.PROJECT == "惠利玛":
  582. # if "小苏" in settings.Company:
  583. # logo_path = r"resources\LOGO\xiaosushuoxie\logo.png"
  584. # elif "惠利玛" in settings.Company:
  585. # logo_path = r"resources\LOGO\HLM\logo.png"
  586. # else:
  587. # pass
  588. if not logo_path:
  589. logo_im = Image.new("RGBA", (1600, 1600), (0, 0, 0, 0))
  590. else:
  591. if os.path.exists(logo_path):
  592. logo_im = Image.open(logo_path)
  593. if logo_im.mode != 'RGBA':
  594. logo_im = logo_im.convert('RGBA')
  595. else:
  596. logo_im = Image.new("RGBA", (1600, 1600), (0, 0, 0, 0))
  597. try:
  598. image_bg.paste(logo_im, (0, 0), logo_im)
  599. except Exception as e:
  600. alpha_mask = logo_im.split()[3]
  601. image_bg.paste(logo_im, (0, 0), alpha_mask)
  602. out_pci_factor = float(
  603. 1
  604. if settings.getSysConfigs("basic_configs", "image_sharpening", "1") == ""
  605. else settings.getSysConfigs("basic_configs", "image_sharpening", "1")
  606. )
  607. # image_bg = image_bg.resize((out_pic_size, out_pic_size), Image.BICUBIC)
  608. if out_pci_factor > 1.0:
  609. print("图片锐化处理")
  610. image_bg = sharpen_image(image_bg, factor=out_pci_factor)
  611. out_pci_mode = "." + settings.getSysConfigs(
  612. "basic_configs", "image_out_format", "png"
  613. )
  614. for imageSize in out_pic_size:
  615. dot_index = out_path.rfind(".")
  616. if dot_index != -1:
  617. # 拆分文件路径和后缀
  618. file_without_suffix = out_path[:dot_index]
  619. suffix = out_path[dot_index + 1 :]
  620. else:
  621. file_without_suffix = out_path
  622. suffix = ""
  623. # 单独拼接字符串示例
  624. image_size_int = int(imageSize)
  625. image_size_str = str(imageSize)
  626. new_file_path = f"{file_without_suffix}_{image_size_str}.{suffix}"
  627. if image_size_int < 3000:
  628. image_bg = image_bg.resize(
  629. (image_size_int, image_size_int), resample=settings.RESIZE_IMAGE_MODE
  630. )
  631. if out_pci_mode == ".jpg":
  632. self.saver.save_image(
  633. image=image_bg,
  634. file_path=new_file_path,
  635. save_mode="jpg",
  636. quality=None,
  637. dpi=None,
  638. _format="JPEG",
  639. )
  640. # save_image_by_thread(image_bg, out_path, save_mode="jpg", quality=None, dpi=None, _format="JPEG")
  641. # image_bg.save(out_path, format="JPEG")
  642. elif out_pci_mode == ".png":
  643. self.saver.save_image(
  644. image=image_bg,
  645. file_path=new_file_path,
  646. save_mode="jpg",
  647. quality=100,
  648. dpi=(300, 300),
  649. _format="JPEG",
  650. )
  651. else:
  652. new_format = out_pci_mode.split(".")[-1]
  653. self.saver.save_image(
  654. image=image_bg,
  655. file_path=new_file_path,
  656. save_mode=new_format,
  657. quality=100,
  658. dpi=(300, 300),
  659. _format=new_format,
  660. )
  661. # save_image_by_thread(image_bg, out_path, save_mode="jpg", quality=100, dpi=(300, 300), _format="JPEG")
  662. # image_bg.save(out_path, quality=100, dpi=(300, 300), format="JPEG")
  663. else:
  664. new_format = out_pci_mode.split(".")[-1]
  665. self.saver.save_image(
  666. image=image_bg,
  667. file_path=new_file_path,
  668. save_mode=new_format,
  669. _format=new_format,
  670. )
  671. # image_bg.save(out_path)
  672. if output_queue is not None:
  673. output_queue.put(True)
  674. return True
  675. def get_scale(self,base_by_box, image_size):
  676. box_width, box_height = int(base_by_box[0]), int(base_by_box[1])
  677. width, height = image_size[0], image_size[1]
  678. if box_width / box_height < width / height:
  679. scale = box_width / width
  680. else:
  681. scale = box_height / height
  682. return scale