grenerate_main_image_test.py 30 KB

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