1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
| import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont
class CvCommonUtils:
@staticmethod def read_img_by_byte(image_bytes): nparr = np.frombuffer(image_bytes, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) return img
@staticmethod def read_img(filename, mode=cv2.IMREAD_COLOR): raw_data = np.fromfile(filename, dtype=np.uint8) img = cv2.imdecode(raw_data, mode) return img
@staticmethod def gray(image): """ 将图像灰度化 """ return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
@staticmethod def is_binary_image(image, tolerance=1e-5): """ 判断图像是否为二值化图像 :param image: 输入的图像 :param tolerance: 用于处理浮点数精度和噪声的容差,默认为 1e - 5 :return: 如果是二值化图像返回 True,否则返回 False """ if len(image.shape) > 2: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image_normalized = image.astype(np.float32) / 255.0
unique_values = np.unique( np.round(image_normalized, decimals=int(-np.log10(tolerance))) )
return len(unique_values) <= 2
@staticmethod def binary(image): """ 将图像二值化 """ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) average_gray = np.mean(gray_image)
ret, bin_image = cv2.threshold(gray_image, average_gray, 255, cv2.THRESH_BINARY) return bin_image
@staticmethod def eroding(image): kernel = np.ones((3, 3), np.uint8) eroded_image = cv2.erode(image, kernel, iterations=1) return eroded_image
@staticmethod def dilate(image): kernel = np.ones((2, 2), np.uint8) dilated_image = cv2.dilate(image, kernel, iterations=1) return dilated_image
@staticmethod def eroding_dilate(image): eroded_image = CvCommonUtils.eroding(image) return CvCommonUtils.dilate(eroded_image)
@staticmethod def sub_img(image, rect): """ 获取区域图像 """ y_start, y_end = rect[1], rect[1] + rect[3] x_start, x_end = rect[0], rect[0] + rect[2] return image[y_start:y_end, x_start:x_end]
@staticmethod def is_smear_card(image, rect): """ 判断指定区域是否存在涂卡行为 """ sub_image = image[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]] gray_image = cv2.cvtColor(sub_image, cv2.COLOR_BGR2GRAY) ret, bin_image = cv2.threshold(gray_image, 200, 255, cv2.THRESH_BINARY) count = cv2.countNonZero(bin_image) total = rect[2] * rect[3] rate = 1.0 * (total - count) / total return rate > 0.7
@staticmethod def get_mat32(source_image): target_size = (32, 32)
source_height, source_width = source_image.shape[:2]
target_height, target_width = target_size
scale_x = target_width / source_width scale_y = target_height / source_height scale = min(scale_x, scale_y)
new_width = int(source_width * scale) new_height = int(source_height * scale)
resized_image = cv2.resize(source_image, (new_width, new_height))
target_image = np.ones(target_size, np.uint8) * 255
start_x = (target_width - new_width) // 2 start_y = (target_height - new_height) // 2
target_image[start_y:start_y + new_height, start_x:start_x + new_width] = resized_image
return target_image
@staticmethod def remove_lines(image):
tempImg = image.copy() rows, cols = tempImg.shape[:2]
empty_lines_hor = [] empty_lines_ver = []
for y in range(rows): row = tempImg[y, :]
if np.count_nonzero(row == 0) / row.size > 0.9: empty_lines_hor.append(y)
for x in range(cols): col = tempImg[:, x]
if np.count_nonzero(col == 0) / col.size > 0.9: empty_lines_ver.append(x)
for row in empty_lines_hor: if row - 1 >=0: tempImg[row-1, :] = 255
tempImg[row, :] = 255
if row + 1 < rows: tempImg[row+1, :] = 255
for col in empty_lines_ver: if col - 1 >=0: tempImg[:, col-1] = 255
tempImg[:, col] = 255
if col + 1 < cols: tempImg[:, col+1] = 255
return tempImg
@staticmethod def get_line_rect_list(img): """ 获取有内容的区域列表 :param img: 输入图像 :return: 有内容区域的矩形列表 """ rows, cols = img.shape[:2]
empty_lines = []
for y in range(rows): row = img[y, :]
count = cv2.countNonZero(row)
if count / cols > 0.95: empty_lines.append(y)
last_num = 0 num_arr_list = []
for line_num in empty_lines: if line_num - last_num >= 5: num_arr_list.append((last_num, line_num)) last_num = line_num
rect_list = []
for item in num_arr_list: rect_list.append( (0, item[0], cols, item[1] - item[0]) )
return rect_list
@staticmethod def find_contours(image): """ 查找图像轮廓 """ contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) return contours
@staticmethod def is_rect_contained(rect1, rect2): """ 判断矩形框互相包含关系 """ return (rect1[0] >= rect2[0] and rect1[1] >= rect2[1] and (rect1[0] + rect1[2]) <= (rect2[0] + rect2[2]) and (rect1[1] + rect1[3]) <= (rect2[1] + rect2[3]))
@staticmethod def is_intersecting(rect1, rect2): """ 判断两个矩形是否相交 :param rect1: :param rect2: :return: """ x1, y1, width1, height1 = rect1 x2, y2, width2, height2 = rect2
right1 = x1 + width1 bottom1 = y1 + height1
right2 = x2 + width2 bottom2 = y2 + height2
return not (x1 >= right2 or right1 <= x2 or y1 >= bottom2 or bottom1 <= y2)
@staticmethod def get_rect_all_by_img(img): """ 从图像中提取矩形区域 :param img: 输入图像(灰度图) :return: 提取到的矩形区域列表 """ contours = CvCommonUtils.find_contours(img) rect_list = [] for contour in contours: rect = cv2.boundingRect(contour) x, y, w, h = rect if 4 < w < 100 and 8 < h < 100: rect_list.append(rect) return rect_list
@staticmethod def get_rect_by_img(img): """ 从图像中提取矩形区域 :param img: 输入图像(灰度图) :return: 提取到的矩形区域列表 """ contours = CvCommonUtils.find_contours(img) rect_list = [] for contour in contours: rect = cv2.boundingRect(contour) x, y, w, h = rect if 6 < w < 60 and 10 < h < 60: rect_list.append(rect)
filtered_list = [] for current_rect in rect_list: is_contained = False for other_rect in rect_list: if current_rect != other_rect and CvCommonUtils.is_rect_contained(current_rect, other_rect): is_contained = True break if not is_contained: filtered_list.append(current_rect) return filtered_list
@staticmethod def cv2AddChineseText(img, text, position, textColor=(255, 0, 0), textSize=20): if isinstance(img, np.ndarray): img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) fontStyle = ImageFont.truetype("simsun.ttc", textSize, encoding="utf-8") draw.text(position, text, textColor, font=fontStyle) return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
@staticmethod def write_txt(img, txt, rect):
text_org = (rect[0], rect[1])
return CvCommonUtils.cv2AddChineseText(img, txt, text_org)
|