opencv常用函数合集

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)

 

 

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值