1.读取图片
img = cv2.imread("<img_path>") #读取图片,转为三通道
img = cv2.imread("<img_path>", 0) #读取图片,转为灰度图
img = cv2.imread("<img_path>", cv2.IMREAD_UNCHANGED) #保持图片原来的通道
2.保存图片
cv2.imwrite("<file_path>",img) #记得文件路径要加图片后缀
3.展示图片
def cvshow(img, wname=None):
if not wname:
cv2.namedWindow("img", 0)
cv2.resizeWindow("img", int(img.shape[1] / 2), int(img.shape[0] / 2))
cv2.imshow('img', img)
else:
cv2.namedWindow(wname, 0)
cv2.resizeWindow(wname, int(img.shape[1] / 2), int(img.shape[0] / 2))
cv2.imshow(wname, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
4.图片二值化
def binary(img, th):
_, result = cv2.threshold(img, th, 255, cv2.THRESH_BINARY)
return result
5.找图片轮廓
def findContours(img):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
x, y, w, h = (0, 0, 0, 0)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 50:
x, y, w, h = cv2.boundingRect(cnt)
x = int(x)
y = int(y)
w = int(w)
h = int(h)
return x, y, w, h, area
6.填充图片
def copyMake(img, sy, sx):
sy = int(sy)
sx = int(sx)
if len(img.shape) >= 3:
img = cv2.copyMakeBorder(img, sy, sy, sx, sx, cv2.BORDER_CONSTANT, value=(255, 255, 255))
else:
img = cv2.copyMakeBorder(img, sy, sy, sx, sx, cv2.BORDER_CONSTANT, value=(0, 0, 0))
return img
7.两个图片merge
def alphaMerge(back_img, front_img, front_mask):
# 3C, 1C(上衣mask),3C, 1C
alpha = cv2.merge((front_mask, front_mask, front_mask))
alpha = alpha.astype(float) / 255
foreground = cv2.multiply(alpha, front_img.astype(float))
background = cv2.multiply((1 - alpha), back_img.astype(float))
outImage = foreground + background
return outImage.astype(np.uint8)