image_deal_base_func.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import cv2
  2. import numpy as np
  3. from PIL import Image, ImageEnhance, ImageFilter, ImageOps
  4. import settings
  5. # 锐化图片
  6. def sharpen_image(img, factor=1.0):
  7. # 创建一个ImageEnhance对象
  8. enhancer = ImageEnhance.Sharpness(img)
  9. # 应用增强,值为0.0给出模糊图像,1.0给出原始图像,大于1.0给出锐化效果
  10. # 调整这个值来增加或减少锐化的程度
  11. sharp_img = enhancer.enhance(factor)
  12. return sharp_img
  13. def to_resize(_im, width=None, high=None) -> Image:
  14. _im_x, _im_y = _im.size
  15. if width and high:
  16. if _im_x >= _im_y:
  17. high = None
  18. else:
  19. width = None
  20. if width:
  21. re_x = int(width)
  22. re_y = int(_im_y * re_x / _im_x)
  23. else:
  24. re_y = int(high)
  25. re_x = int(_im_x * re_y / _im_y)
  26. _im = _im.resize((re_x, re_y),resample=settings.RESIZE_IMAGE_MODE)
  27. return _im
  28. def pil_to_cv2(pil_image):
  29. # 将 PIL 图像转换为 RGB 或 RGBA 格式
  30. if pil_image.mode != 'RGBA':
  31. pil_image = pil_image.convert('RGBA')
  32. # 将 PIL 图像转换为 numpy 数组
  33. cv2_image = np.array(pil_image)
  34. # 由于 PIL 的颜色顺序是 RGB,而 OpenCV 的颜色顺序是 BGR,因此需要交换颜色通道
  35. cv2_image = cv2.cvtColor(cv2_image, cv2.COLOR_RGBA2BGRA)
  36. return cv2_image
  37. def cv2_to_pil(cv_img):
  38. return Image.fromarray(cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB))
  39. def get_mini_crop_img(img):
  40. old_x, old_y = img.size
  41. x1, y1, x2, y2 = img.getbbox()
  42. goods_w, goods_h = x2 - x1, y2 - y1
  43. _w, _h = int(goods_w / 10), int(goods_h / 10) # 上下左右扩展位置
  44. new_x1, new_y1, new_x2, new_y2 = x1 - _w, y1 - _h, x2 + _w, y2 + _h # 防止超限
  45. new_x1 = 0 if new_x1 < 0 else new_x1
  46. new_y1 = 0 if new_y1 < 0 else new_y1
  47. new_x2 = old_x if new_x2 > old_x else new_x2
  48. new_y2 = old_y if new_y2 > old_y else new_y2
  49. img = img.crop((new_x1, new_y1, new_x2, new_y2)) # 切图
  50. box = (new_x1, new_y1, new_x2, new_y2)
  51. return img, box
  52. def expand_mask(mask, expansion_radius=5, blur_radius=0):
  53. # 对蒙版进行膨胀处理
  54. mask = mask.filter(ImageFilter.MaxFilter(expansion_radius * 2 + 1))
  55. # 应用高斯模糊滤镜
  56. if blur_radius > 0:
  57. mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))
  58. return mask
  59. def expand_or_shrink_mask(pil_image, expansion_radius=5, iterations=1, blur_radius=0):
  60. """
  61. 对输入的PIL黑白图像(掩膜)进行膨胀或腐蚀操作,以扩大或缩小前景区域。
  62. :param pil_image: 输入的PIL黑白图像对象
  63. :param expansion_radius: 结构元素大小,默认是一个3x3的小正方形;负值表示收缩
  64. :param iterations: 操作迭代次数,默认为1次
  65. :param blur_radius: 高斯模糊的半径,默认不应用模糊
  66. :return: 修改后的PIL黑白图像对象
  67. """
  68. # 将PIL图像转换为numpy数组,并确保其为8位无符号整数类型
  69. img_np = np.array(pil_image).astype(np.uint8)
  70. # 如果不是二值图像,则应用阈值处理
  71. if len(np.unique(img_np)) > 2: # 检查是否为二值图像
  72. _, img_np = cv2.threshold(img_np, 127, 255, cv2.THRESH_BINARY)
  73. # 定义结构元素(例如正方形)
  74. abs_expansion_radius = abs(expansion_radius)
  75. kernel = np.ones((abs_expansion_radius, abs_expansion_radius), np.uint8)
  76. # 根据expansion_radius的符号选择膨胀或腐蚀操作
  77. if expansion_radius >= 0:
  78. modified_img_np = cv2.dilate(img_np, kernel, iterations=iterations)
  79. else:
  80. modified_img_np = cv2.erode(img_np, kernel, iterations=iterations)
  81. # 如果提供了blur_radius,则应用高斯模糊
  82. if blur_radius > 0:
  83. modified_img_np = cv2.GaussianBlur(
  84. modified_img_np, (blur_radius * 2 + 1, blur_radius * 2 + 1), 0
  85. )
  86. # 将numpy数组转换回PIL图像
  87. modified_pil_image = Image.fromarray(modified_img_np)
  88. return modified_pil_image
  89. def find_lowest_non_transparent_points(cv2_png):
  90. # cv2_png 为cv2格式的带有alpha通道的图片
  91. alpha_channel = cv2_png[:, :, 3]
  92. """使用Numpy快速查找每列的最低非透明点"""
  93. h, w = alpha_channel.shape
  94. # 创建一个掩码,其中非透明像素为True
  95. mask = alpha_channel > 0
  96. # 使用np.argmax找到每列的第一个非透明像素的位置
  97. # 因为是从底部向上找,所以需要先翻转图像
  98. flipped_mask = np.flip(mask, axis=0)
  99. min_y_values = h - np.argmax(flipped_mask, axis=0) - 1
  100. # 将全透明列的值设置为-1
  101. min_y_values[~mask.any(axis=0)] = -1
  102. return min_y_values
  103. def draw_shifted_line(
  104. image,
  105. min_y_values,
  106. shift_amount=15,
  107. one_line_pos=(0, 100),
  108. line_color=(0, 0, 0),
  109. line_thickness=20,
  110. app=None,
  111. crop_image_box=None,
  112. ):
  113. """
  114. image:jpg cv2格式的原始图
  115. min_y_values 透明图中,不透明区域的最低那条线
  116. shift_amount:向下偏移值
  117. line_color:线颜色
  118. line_thickness:线宽
  119. """
  120. # 将最低Y值向下迁移20个像素,但确保不超过图片的高度
  121. # 创建空白图片
  122. image = np.ones((image.shape[0], image.shape[1], 3), dtype=np.uint8) * 255
  123. # 对线条取转成图片
  124. shifted_min_y_values = np.clip(min_y_values + shift_amount, 0, image.shape[0] - 1)
  125. # 使用Numpy索引批量绘制直线
  126. min_y_threshold = 50 # Y轴像素小于50的不处理
  127. valid_x = (shifted_min_y_values >= min_y_threshold) & (shifted_min_y_values != -1)
  128. # print("valid_x", len(valid_x))
  129. # 对曲线取平均值
  130. # # 对曲线取平均值
  131. # min_y = np.max(min_y_values)
  132. # min_y_values_2 = min_y_values + min_y
  133. # min_y_values_2 = min_y_values_2 / 2
  134. # min_y_values_2 = min_y_values_2.astype(int)
  135. # shifted_min_y_values = np.clip(min_y_values_2 + shift_amount, 0, image.shape[0] - 1)
  136. if settings.SHADOW_PROCESSING == 0:
  137. if crop_image_box:
  138. # 800像素宽;鞋子前后20%进行移除
  139. shoe_width = crop_image_box[2] - crop_image_box[0]
  140. _half_show_width = int(shoe_width * 0.15)
  141. valid_x[: crop_image_box[0] + _half_show_width] = False
  142. valid_x[crop_image_box[2] - _half_show_width :] = False
  143. x_coords = np.arange(image.shape[1])[valid_x]
  144. y_start = shifted_min_y_values[valid_x]
  145. y_end = y_start + line_thickness
  146. # todo 使用Numpy广播机制创建线条区域的索引
  147. # todo 鞋子曲线线条
  148. if settings.SHADOW_PROCESSING == 0:
  149. for x, start, end in zip(x_coords, y_start, y_end):
  150. image[start:end, x, :3] = line_color # 只修改RGB通道
  151. # 计算整个图像的最低非透明点
  152. lowest_y = (
  153. np.max(min_y_values[min_y_values != -1]) if np.any(min_y_values != -1) else -1
  154. )
  155. # 绘制原最低非透明点处的线
  156. cv2.line(
  157. image,
  158. (one_line_pos[0], lowest_y + settings.LOWER_Y),
  159. (one_line_pos[1], lowest_y + 5),
  160. line_color,
  161. thickness=line_thickness,
  162. )
  163. # 调整 _y = lowest_y + 18
  164. _y = lowest_y + 200
  165. if _y > image.shape[0]: # 超过图片尺寸
  166. _y = image.shape[0] - settings.CHECK_LOWER_Y
  167. return image, _y
  168. def clean_colors(img):
  169. # 转成灰度图
  170. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  171. return img
  172. def calculated_shadow_brightness(img: Image):
  173. # 打开图片并转换为灰度模式
  174. image = img.convert('L')
  175. # 将图片数据转为numpy数组
  176. image_data = np.array(image)
  177. # 创建布尔掩码以识别非白色区域
  178. non_white_mask = image_data < 252
  179. # 使用掩码提取非白色像素的亮度值
  180. non_white_values = image_data[non_white_mask]
  181. # print(len(non_white_values),len(image_data))
  182. # 如果存在非白色像素,则计算平均亮度;否则返回0
  183. if len(non_white_values) > 0:
  184. average_brightness = np.mean(non_white_values)
  185. else:
  186. average_brightness = 0 # 没有非白色像素时的情况
  187. return average_brightness
  188. def levels_adjust(img, Shadow, Midtones, Highlight, OutShadow, OutHighlight, Dim):
  189. # 色阶处理
  190. # img 为cv2格式
  191. # dim = 3的时候调节RGB三个分量, 0调节B,1调节G,2调节R
  192. if Dim == 3:
  193. mask_shadow = img < Shadow
  194. img[mask_shadow] = Shadow
  195. mask_Highlight = img > Highlight
  196. img[mask_Highlight] = Highlight
  197. else:
  198. mask_shadow = img[..., Dim] < Shadow
  199. img[mask_shadow] = Shadow
  200. mask_Highlight = img[..., Dim] > Highlight
  201. img[mask_Highlight] = Highlight
  202. if Dim == 3:
  203. Diff = Highlight - Shadow
  204. rgbDiff = img - Shadow
  205. clRgb = np.power(rgbDiff / Diff, 1 / Midtones)
  206. outClRgb = clRgb * (OutHighlight - OutShadow) / 255 + OutShadow
  207. data = np.array(outClRgb * 255, dtype='uint8')
  208. img = data
  209. else:
  210. Diff = Highlight - Shadow
  211. rgbDiff = img[..., Dim] - Shadow
  212. clRgb = np.power(rgbDiff / Diff, 1 / Midtones)
  213. outClRgb = clRgb * (OutHighlight - OutShadow) / 255 + OutShadow
  214. data = np.array(outClRgb * 255, dtype='uint8')
  215. img[..., Dim] = data
  216. return img
  217. def calculate_average_brightness_opencv(img_gray, rows_to_check):
  218. # 二值化的图片 CV对象
  219. # 计算图片亮度
  220. height, width = img_gray.shape
  221. brightness_list = []
  222. for row in rows_to_check:
  223. if 0 <= row < height:
  224. # 直接计算该行的平均亮度
  225. row_data = img_gray[row, :]
  226. average_brightness = np.mean(row_data)
  227. brightness_list.append(average_brightness)
  228. else:
  229. print(f"警告:行号{row}超出图片范围,已跳过。")
  230. return brightness_list