算法暴露接口(xhs、dy、ks、wx、hnw)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

205 lines
7.5 KiB

7 months ago
  1. import io
  2. import random
  3. import time
  4. import cv2 as cv
  5. import numpy as np
  6. from PIL import Image
  7. from scipy import signal
  8. # format_list = [0, 10, 16, 6, 13, 3, 9, 15, 11, 19, 14, 18, 4, 12, 2, 1, 8, 17, 7, 5]
  9. # this.canvasCtx.drawImage(this.img,
  10. # 30 * i, 开始剪切的 x 坐标位置。
  11. # 0, 开始剪切的 y 坐标位置。
  12. # 30, 被剪切图像的宽度。
  13. # 400, 被剪切图像的高度。
  14. # 30 * keylist[i] / 1.5, 在画布上放置图像的 x 坐标位置
  15. # 0, 在画布上放置图像的 y 坐标位置。
  16. # offset / 1.5, 要使用的图像的宽度。(伸展或缩小图像)
  17. # 200) 要使用的图像的高度。(伸展或缩小图像)
  18. def format_slide_img(raw_img: bytes, format_list: list) -> bytes:
  19. fp = io.BytesIO(raw_img)
  20. img = Image.open(fp)
  21. image_dict = {}
  22. offset = 30
  23. for i in range(len(format_list)):
  24. box = (i * offset, 0, offset + (i * offset), 400) # 左(起始),上(不变),右(宽),下(不变)
  25. image_dict[format_list[i]] = img.crop(box)
  26. image_list = []
  27. for i in sorted(image_dict):
  28. image_list.append(image_dict[i])
  29. image_num = len(image_list)
  30. image_size = image_list[0].size
  31. height = image_size[1]
  32. width = image_size[0]
  33. new_img = Image.new('RGB', (image_num * width, height), 255)
  34. x = y = 0
  35. for img in image_list:
  36. new_img.paste(img, (x, y))
  37. x += width
  38. box = (0, 0, 600, 400)
  39. new_img = new_img.crop(box)
  40. # 保存图片
  41. processClickImgIoFlow = io.BytesIO()
  42. new_img.save(processClickImgIoFlow, format="JPEG")
  43. return processClickImgIoFlow.getvalue()
  44. # with open("test.jpg", "wb") as f:
  45. # f.write(processClickImgIoFlow.getvalue())
  46. # 1
  47. def discern_gap(gapImage: bytes, sliderImage: bytes, show=False):
  48. def edge_detection(rawimg):
  49. def tracebar(x):
  50. threshold1 = cv.getTrackbarPos('threshold1', 'Test')
  51. threshold2 = cv.getTrackbarPos('threshold2', 'Test')
  52. edged_img = cv.Canny(img_Gaussian, threshold1, threshold2)
  53. cv.imshow("edged_img", edged_img)
  54. image = np.asarray(bytearray(rawimg), dtype="uint8")
  55. img = cv.imdecode(image, cv.IMREAD_COLOR)
  56. grep_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  57. # 高斯滤波 高斯滤波是通过对输入数组的每个点与输入的高斯滤波模板执行卷积计算然后将这些结果一块组成了滤波后的输出数组,
  58. # 通俗的讲就是高斯滤波是对整幅图像进行加权平均的过程,每一个像素点的值都由其本身和邻域内的其他像素值经过加权平均后得到。
  59. # 高斯滤波的具体操作是:用一个模板(或称卷积、掩模)扫描图像中的每一个像素,用模板确定的邻域内像素的加权平均灰度值去替代模板中心像素点的值。
  60. img_Gaussian = cv.GaussianBlur(grep_img, (5, 5), 0)
  61. # 用于对图像的边缘检测
  62. edged_img = cv.Canny(img_Gaussian, 25, 45)
  63. if show:
  64. cv.namedWindow("Test")
  65. # cv.imshow('raw_img', img)
  66. # cv.imshow('grep_img', grep_img)
  67. cv.imshow('img_Gaussian', img_Gaussian)
  68. cv.createTrackbar("threshold1", "Test", 0, 255, tracebar)
  69. cv.createTrackbar("threshold2", "Test", 0, 255, tracebar)
  70. cv.imshow('edged_img', edged_img)
  71. cv.waitKey(3000)
  72. cv.destroyAllWindows()
  73. return edged_img
  74. def similarity_calculation(background, slider):
  75. result = cv.matchTemplate(background, slider, cv.TM_CCOEFF_NORMED)
  76. # 获取一个/组int类型的索引值在一个多维数组中的位置。
  77. # x, y = np.unravel_index(result.argmax(), result.shape)
  78. min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
  79. return max_loc
  80. """计算滑动距离方法"""
  81. gap = edge_detection(gapImage)
  82. slider = edge_detection(sliderImage)
  83. x, y = similarity_calculation(gap, slider)
  84. # print('需要滑动距离', x, y)
  85. # todo 返回的距离
  86. return x
  87. def discern_gap2(gap_path, slider_path, save=False):
  88. def pic2grep(pic_path, type) -> np.ndarray:
  89. pic_path_rgb = cv.imread(pic_path)
  90. pic_path_gray = cv.cvtColor(pic_path_rgb, cv.COLOR_BGR2GRAY)
  91. if save:
  92. cv.imwrite(f"./{type}.jpg", pic_path_gray)
  93. return pic_path_gray
  94. def canny_edge(image_array: np.ndarray, show=False) -> np.ndarray:
  95. can = cv.Canny(image_array, threshold1=200, threshold2=300)
  96. if show:
  97. cv.imshow('candy', can)
  98. cv.waitKey()
  99. cv.destroyAllWindows()
  100. return can
  101. def clear_white(img: str, show=False) -> np.ndarray:
  102. img = cv.imread(img)
  103. rows, cols, channel = img.shape
  104. min_x = 255
  105. min_y = 255
  106. max_x = 0
  107. max_y = 0
  108. for x in range(1, rows):
  109. for y in range(1, cols):
  110. t = set(img[x, y])
  111. if len(t) >= 2:
  112. if x <= min_x:
  113. min_x = x
  114. elif x >= max_x:
  115. max_x = x
  116. if y <= min_y:
  117. min_y = y
  118. elif y >= max_y:
  119. max_y = y
  120. img1 = img[min_x:max_x, min_y:max_y]
  121. if show:
  122. cv.imshow('img1', img1)
  123. cv.waitKey()
  124. cv.destroyAllWindows()
  125. return img1
  126. def convolve2d(bg_array: np.ndarray, fillter: np.ndarray) -> np.ndarray:
  127. bg_h, bg_w = bg_array.shape[:2]
  128. fillter = fillter[::-1,::-1]
  129. fillter_h, fillter_w = fillter.shape[:2]
  130. c_full = signal.convolve2d(bg_array, fillter, mode="full")
  131. kr, kc = fillter_h // 2, fillter_w // 2
  132. c_same = c_full[
  133. fillter_h - kr - 1: bg_h + fillter_h - kr - 1,
  134. fillter_w - kc - 1: bg_w + fillter_w - kc - 1,
  135. ]
  136. return c_same
  137. def find_max_point(arrays: np.ndarray, search_on_horizontal_center=False) -> tuple:
  138. max_point = 0
  139. max_point_pos = None
  140. array_rows, array_cols = arrays.shape
  141. if search_on_horizontal_center:
  142. for col in range(array_cols):
  143. if arrays[array_rows // 2, col] > max_point:
  144. max_point = arrays[array_rows // 2, col]
  145. max_point_pos = col, array_rows // 2
  146. else:
  147. for row in range(array_rows):
  148. for col in range(array_cols):
  149. if arrays[row, col] > max_point:
  150. max_point = arrays[row, col]
  151. max_point_pos = col, row
  152. return max_point_pos
  153. gap_grep = pic2grep(gap_path, "gap")
  154. gap_can = canny_edge(gap_grep, False)
  155. clear_slider = cv.imread(slider_path) # clear_white(slider_path, False)
  156. slider_can = canny_edge(clear_slider, False)
  157. convolve2d_result = convolve2d(gap_can, slider_can)
  158. result = find_max_point(convolve2d_result, True)
  159. print(result)
  160. def recognize_gap(bg, fg, is_show=False):
  161. if isinstance(bg, str):
  162. with open(fg, "rb") as f:
  163. sliderImage = f.read()
  164. # print(sliderImage)
  165. with open(bg, "rb") as f:
  166. gapImage = f.read()
  167. else:
  168. sliderImage = fg
  169. gapImage = bg
  170. res = discern_gap(gapImage,sliderImage, is_show)
  171. return res
  172. if __name__ == '__main__':
  173. with open("../kuaishou/tmp/img.png", "rb") as f:
  174. sliderImage = f.read()
  175. # print(sliderImage)
  176. with open("../kuaishou/tmp/img_1.png", "rb") as f:
  177. gapImage = f.read()
  178. res = discern_gap(gapImage,sliderImage, True)
  179. print(res * 56/122)
  180. # print(random.randint(100, 200))
  181. # 256