世界坐标系转为像素坐标系
point3d = np.array([-55.0, 15.0, -5.0])
point3d = np.mat(1000 * point3d)
point2d, _ = cv2.projectPoints(point3d, param['rotate_vec'], param['trans_vec'], param['in_param'], param['dist_vec'])
根据相机外参的旋转向量得到旋转矩阵
rvec = np.array([[1.755126, 0.9954, -0.773907]])
rot_mat, _ = cv2.Rodrigues(rvec)
图像减法
# 两张图相减,小于0的像素默认为0
sub = cv2.subtract(fg_masked, bg_masked)
# 计算两幅图的差的绝对值
sub = cv2.absdiff(bg, fg)
图像平滑(去噪):高斯滤波,中值滤波,双边滤波,均值滤波
thresh = cv2.GaussianBlur(img, (5, 5), 0)
thresh = cv2.medianBlur(img, 5)
thresh = cv2.bilateralFilter(img, 9, 75, 75)
thresh = cv2.blur(img, (5, 5))
开运算(先腐蚀,后膨胀)
thresh = cv2.erode(thresh, (50,50), iterations=1)
thresh = cv2.dilate(thresh, (5,5), iterations=1)
# 形态学开运算
opening = cv2.morphologyEx(threshold,cv2.MORPH_OPEN,kernel)
# 闭运算
closing = cv2.morphologyEx(threshold,cv2.MORPH_CLOSE,kernel)
图像二值化
ret, thresh = cv2.threshold(mask_img, 0, 255, 0)
提取轮廓,画出轮廓
im, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
frame = cv2.drawContours(frame, contours, -1, (0, 255, 255), 3)
计算轮廓面积,定位轮廓质心位置
for contour in contours:
area = cv2.contourArea(contour)
mu = cv2.moments(contour, False)
mc = [mu['m10'] / mu['m00'], mu['m01'] / mu['m00']]
轮廓凸包,轮廓外接矩形,最小外接矩形
hull = cv2.convexHull(contour)
x, y, w, h = cv2.boundingRect(contour)
min_rect = cv2.minAreaRect(contour)
判断一点是否在轮廓内
flag = cv2.pointPolygonTest(occu_point, center, False)
图像mask操作
fg = cv2.imread(img_path)
rectangle = np.zeros(fg.shape[:2], dtype="uint8")
txtp = os.path.join(txt_dir, img.split('.')[0]+'.txt')
with open(txtp, 'r') as f:
res1 = [[float(j) for j in x.split()] for x in f.read().splitlines()]
for obj in res1:
cls, cx, cy, cw, ch = obj
xmin = int((cx - 0.5 * cw) * 1920)
ymin = int((cy - 0.5 * ch) * 1080)
xmax = int((cx + 0.5 * cw) * 1920)
ymax = int((cy + 0.5 * ch) * 1080)
cv2.rectangle(rectangle, (xmin, ymin), (xmax, ymax), 255, -1)
fg_masked = cv2.bitwise_and(fg, fg, mask=rectangle)
cv2.imshow('img', fg_masked)
画直线,多边形,矩形,圆
cv2.line(frame, corners[1], corners[5], (255, 0, 0), 1)
cv2.polylines(frame, [hull], True, (0, 255, 0), 2)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.circle(frame, (int(mc[0]), int(mc[1])), 7, (0, 255, 0), -1)
多边形填充
# 填充任意多边形
cv2.fillPoly(frame, [area1], (255, 0, 0))
# 填充凸多边形
cv2.fillConvexPoly(frame, area4, (255, 255, 255))
图片缩放
# 等比例
frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
# 固定尺寸
mask_img = cv2.resize(mask_img, (1920, 1080))