image_deal_base_func.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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_or_shrink_mask(pil_image, expansion_radius=5, iterations=1, blur_radius=0):
  53. """
  54. 对输入的PIL黑白图像(掩膜)进行膨胀或腐蚀操作,以扩大或缩小前景区域。
  55. :param pil_image: 输入的PIL黑白图像对象
  56. :param expansion_radius: 结构元素大小,默认是一个3x3的小正方形;负值表示收缩
  57. :param iterations: 操作迭代次数,默认为1次
  58. :param blur_radius: 高斯模糊的半径,默认不应用模糊
  59. :return: 修改后的PIL黑白图像对象
  60. """
  61. # 将PIL图像转换为numpy数组,并确保其为8位无符号整数类型
  62. img_np = np.array(pil_image).astype(np.uint8)
  63. # 如果不是二值图像,则应用阈值处理
  64. if len(np.unique(img_np)) > 2: # 检查是否为二值图像
  65. _, img_np = cv2.threshold(img_np, 127, 255, cv2.THRESH_BINARY)
  66. # 定义结构元素(例如正方形)
  67. abs_expansion_radius = abs(expansion_radius)
  68. kernel = np.ones((abs_expansion_radius, abs_expansion_radius), np.uint8)
  69. # 根据expansion_radius的符号选择膨胀或腐蚀操作
  70. if expansion_radius >= 0:
  71. modified_img_np = cv2.dilate(img_np, kernel, iterations=iterations)
  72. else:
  73. modified_img_np = cv2.erode(img_np, kernel, iterations=iterations)
  74. # 如果提供了blur_radius,则应用高斯模糊
  75. if blur_radius > 0:
  76. modified_img_np = cv2.GaussianBlur(modified_img_np, (blur_radius * 2 + 1, blur_radius * 2 + 1), 0)
  77. # 将numpy数组转换回PIL图像
  78. modified_pil_image = Image.fromarray(modified_img_np)
  79. return modified_pil_image
  80. def expand_mask(mask, expansion_radius=5, blur_radius=0):
  81. # 对蒙版进行膨胀处理
  82. mask = mask.filter(ImageFilter.MaxFilter(expansion_radius * 2 + 1))
  83. # 应用高斯模糊滤镜
  84. if blur_radius > 0:
  85. mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))
  86. return mask
  87. def find_lowest_non_transparent_points(cv2_png):
  88. # cv2_png 为cv2格式的带有alpha通道的图片
  89. alpha_channel = cv2_png[:, :, 3]
  90. """使用Numpy快速查找每列的最低非透明点"""
  91. h, w = alpha_channel.shape
  92. # 创建一个掩码,其中非透明像素为True
  93. mask = alpha_channel > 0
  94. # 使用np.argmax找到每列的第一个非透明像素的位置
  95. # 因为是从底部向上找,所以需要先翻转图像
  96. flipped_mask = np.flip(mask, axis=0)
  97. min_y_values = h - np.argmax(flipped_mask, axis=0) - 1
  98. # 将全透明列的值设置为-1
  99. min_y_values[~mask.any(axis=0)] = -1
  100. return min_y_values
  101. def draw_shifted_line(image, min_y_values, shift_amount=15,
  102. one_line_pos=(0, 100),
  103. line_color=(0, 0, 0),
  104. line_thickness=20,
  105. app=None):
  106. """
  107. image:jpg cv2格式的原始图
  108. min_y_values 透明图中,不透明区域的最低那条线
  109. shift_amount:向下偏移值
  110. line_color:线颜色
  111. line_thickness:线宽
  112. """
  113. # 将最低Y值向下迁移20个像素,但确保不超过图片的高度
  114. # 创建空白图片
  115. if app:
  116. # TODO 待移除
  117. app.processEvents()
  118. image = np.ones((image.shape[0], image.shape[1], 3), dtype=np.uint8) * 255
  119. # 对线条取转成图片
  120. shifted_min_y_values = np.clip(min_y_values + shift_amount, 0, image.shape[0] - 1)
  121. if app:
  122. # TODO 待移除
  123. app.processEvents()
  124. # 使用Numpy索引批量绘制直线
  125. min_y_threshold = 50 # Y轴像素小于50的不处理
  126. valid_x = (shifted_min_y_values >= min_y_threshold) & (shifted_min_y_values != -1)
  127. if app:
  128. # TODO 待移除
  129. app.processEvents()
  130. # 对曲线取平均值
  131. # # 对曲线取平均值
  132. # min_y = np.max(min_y_values)
  133. # min_y_values_2 = min_y_values + min_y
  134. # min_y_values_2 = min_y_values_2 / 2
  135. # min_y_values_2 = min_y_values_2.astype(int)
  136. # shifted_min_y_values = np.clip(min_y_values_2 + shift_amount, 0, image.shape[0] - 1)
  137. x_coords = np.arange(image.shape[1])[valid_x]
  138. y_start = shifted_min_y_values[valid_x]
  139. y_end = y_start + line_thickness
  140. # 使用Numpy广播机制创建线条区域的索引
  141. for x, start, end in zip(x_coords, y_start, y_end):
  142. image[start:end, x, :3] = line_color # 只修改RGB通道
  143. if app:
  144. # TODO 待移除
  145. app.processEvents()
  146. # 计算整个图像的最低非透明点
  147. lowest_y = np.max(min_y_values[min_y_values != -1]) if np.any(min_y_values != -1) else -1
  148. # 绘制原最低非透明点处的线
  149. cv2.line(image, (one_line_pos[0], lowest_y + 5), (one_line_pos[1], lowest_y + 5), line_color,
  150. thickness=line_thickness)
  151. if app:
  152. # TODO 待移除
  153. app.processEvents()
  154. _y = lowest_y + 18
  155. if _y > image.shape[0]: # 超过图片尺寸
  156. _y = image.shape[0] - 5
  157. return image, _y
  158. def clean_colors(img):
  159. # 转成灰度图
  160. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  161. return img
  162. def calculated_shadow_brightness(img: Image):
  163. # 打开图片并转换为灰度模式
  164. image = img.convert('L')
  165. # 将图片数据转为numpy数组
  166. image_data = np.array(image)
  167. # 创建布尔掩码以识别非白色区域
  168. non_white_mask = image_data < 252
  169. # 使用掩码提取非白色像素的亮度值
  170. non_white_values = image_data[non_white_mask]
  171. # print(len(non_white_values),len(image_data))
  172. # 如果存在非白色像素,则计算平均亮度;否则返回0
  173. if len(non_white_values) > 0:
  174. average_brightness = np.mean(non_white_values)
  175. else:
  176. average_brightness = 0 # 没有非白色像素时的情况
  177. return average_brightness
  178. def levels_adjust(img, Shadow, Midtones, Highlight, OutShadow, OutHighlight, Dim):
  179. # 色阶处理
  180. # img 为cv2格式
  181. # dim = 3的时候调节RGB三个分量, 0调节B,1调节G,2调节R
  182. if Dim == 3:
  183. mask_shadow = img < Shadow
  184. img[mask_shadow] = Shadow
  185. mask_Highlight = img > Highlight
  186. img[mask_Highlight] = Highlight
  187. else:
  188. mask_shadow = img[..., Dim] < Shadow
  189. img[mask_shadow] = Shadow
  190. mask_Highlight = img[..., Dim] > Highlight
  191. img[mask_Highlight] = Highlight
  192. if Dim == 3:
  193. Diff = Highlight - Shadow
  194. rgbDiff = img - Shadow
  195. clRgb = np.power(rgbDiff / Diff, 1 / Midtones)
  196. outClRgb = clRgb * (OutHighlight - OutShadow) / 255 + OutShadow
  197. data = np.array(outClRgb * 255, dtype='uint8')
  198. img = data
  199. else:
  200. Diff = Highlight - Shadow
  201. rgbDiff = img[..., Dim] - Shadow
  202. clRgb = np.power(rgbDiff / Diff, 1 / Midtones)
  203. outClRgb = clRgb * (OutHighlight - OutShadow) / 255 + OutShadow
  204. data = np.array(outClRgb * 255, dtype='uint8')
  205. img[..., Dim] = data
  206. return img
  207. def calculate_average_brightness_opencv(img_gray, rows_to_check):
  208. # 二值化的图片 CV对象
  209. # 计算图片亮度
  210. height, width = img_gray.shape
  211. brightness_list = []
  212. for row in rows_to_check:
  213. if 0 <= row < height:
  214. # 直接计算该行的平均亮度
  215. row_data = img_gray[row, :]
  216. average_brightness = np.mean(row_data)
  217. brightness_list.append(average_brightness)
  218. else:
  219. print(f"警告:行号{row}超出图片范围,已跳过。")
  220. return brightness_list