import numpy as np from matplotlib import pyplot as plt import cv2 as cv def contours_area(cnt): # 计算 countour 的面积 (x, y, w, h) = cv.boundingRect(cnt) return w * h # 载入原图 img = cv.imread('cat.png') # 图像二值化 img_bin = cv.inRange(img, lowerb=(9, 16, 84), upperb=(255, 251, 255)) kernel = np.ones((5, 5), np.uint8) img_bin = cv.erode(img_bin, kernel, iterations=1) img_bin = cv.dilate(img_bin, kernel, iterations=2) contours, hierarchy = cv.findContours(img_bin,cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) img_contours=cv.drawContours(img_bin, contours, -1, (0, 0, 255), 2) #抠图-带罩层的二值化与操作 #img跟它本身进行或/与操作(其实他们的结果是一样的) 在罩层区域(MASK)内进行。罩层区域为0, 黑色。 #二值化操作就是 如果两个img的该点的像素点都不为零则保留原来的取值,否则就是黑色。 mask = img.copy() mask[:] = 0 cv.drawContours(mask, contours, -1, (255,255,255), -1) img_cutout = cv.bitwise_or(img,mask) background=np.zeros_like(img) background[:,:,:]=(150,198,12) new_background = cv.bitwise_or(background, background, mask=cv.bitwise_not(mask)) new_img=cv.add(new_background,img_cutout) cv.imshow('binary',new_img) cv.waitKey(0) cv.destroyAllWindows找错误
时间: 2023-06-06 12:06:07 浏览: 96
这是一个Python函数的开头,用于导入需要使用的库。其中numpy库被导入并重命名为np,用于进行数学计算和数组操作;matplotlib库中的pyplot子库被导入并重命名为plt,用于绘制图形;cv2库被导入并重命名为cv,用于图像处理。
函数名称为contours_area,它的参数是一个轮廓,用于计算该轮廓的面积。
阅读全文