HYJK-Vison-ocr_vehicle_cert.../ocr_vehicle_certificate_vino_noconfig/utils.py

117 lines
3.4 KiB
Python
Raw Permalink Normal View History

2024-12-05 14:24:03 +08:00
import base64
import cv2
import numpy as np
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tobytes()).decode('utf8')
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
def expand_crop(image, box, expand_ratio=0.0):
imgh, imgw, c = image.shape
xmin, ymin, xmax, ymax = box
org_rect = [xmin, ymin, xmax, ymax]
h_half = (ymax - ymin) * (1 + expand_ratio) / 2.
w_half = (xmax - xmin) * (1 + expand_ratio) / 2.
if h_half > w_half * 4 / 3:
w_half = h_half * 0.75
center = [(ymin + ymax) / 2., (xmin + xmax) / 2.]
ymin = max(0, int(center[0] - h_half))
ymax = min(imgh - 1, int(center[0] + h_half))
xmin = max(0, int(center[1] - w_half))
xmax = min(imgw - 1, int(center[1] + w_half))
return image[ymin:ymax, xmin:xmax, :].copy(), [xmin, ymin, xmax, ymax], org_rect
def crop_image_with_box(image, boxes):
crop_res = []
for box in boxes:
crop_image, new_box, ori_box = expand_crop(image, box)
# import cv2
# cv2.imshow('1',crop_image)
# cv2.waitKey(0)
if crop_image is not None:
crop_res.append(crop_image)
return crop_res
def four_point_transform(image, pts):
# # 获取输入坐标点
# (tl, tr, br, bl) = pts
# # 计算输入的w和h的值
# widthA = np.sqrt(((br[0] - bl[0])**2) + ((br[1] - bl[1])**2))
# widthB = np.sqrt(((tr[0] - tl[0])**2) + ((tr[1] - tl[1])**2))
# maxWidth = max(int(widthA), int(widthB))
# heightA = np.sqrt(((tr[0] - br[0])**2) + ((tr[1] - br[1])**2))
# heightB = np.sqrt(((tl[0] - bl[0])**2) + ((tl[1] - bl[1])**2))
# maxHeight = max(int(heightA), int(heightB))
maxWidth = 960
maxHeight = 960
# 变化后对应坐标位置
dst = np.array([[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]],
dtype='float32')
# 计算变换矩阵
warp_mat = cv2.getPerspectiveTransform(np.float32(pts), dst)
warped = cv2.warpPerspective(image, warp_mat, (maxWidth, maxHeight))
return warped
def rect_intersect_area(rect1, rect2):
"""
计算两个矩形的相交面积
rect1, rect2: 形状为(4,)的数组包含[x1, y1, x2, y2]
"""
x1, y1, x2, y2 = rect1
X1, Y1, X2, Y2 = rect2
# 计算相交矩形的坐标
ix1 = max(x1, X1)
iy1 = max(y1, Y1)
ix2 = min(x2, X2)
iy2 = min(y2, Y2)
# 检查是否有相交
if ix1 < ix2 and iy1 < iy2:
# 计算相交面积
area = (ix2 - ix1) * (iy2 - iy1)
return area
else:
return 0
def rect_intersect(rect1, rect2):
"""
计算两个矩形的相交面积
rect1, rect2: 形状为(4,)的数组包含[x1, y1, x2, y2]
"""
x1, y1, x2, y2 = rect1
X1, Y1, X2, Y2 = rect2
# 计算相交矩形的坐标
ix1 = max(x1, X1)
iy1 = max(y1, Y1)
ix2 = min(x2, X2)
iy2 = min(y2, Y2)
# 检查是否有相交
# if ix1 < ix2 and iy1 < iy2:
# 计算相交面积
if (ix2 - ix1) > 10 and (iy2 - iy1) > 10:
return True
else:
return False