参考代码和函数:OpenCV绘图之多边形函数cvFillPoly,cvPolyLine,cvFillConvexPoly
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = np.zeros((100, 100), dtype = np.int8)
print img
print '\n.......\n'
#four points of a monotonic polygon
points = np.array([[1, 1], [1, 98], [98, 98], [98, 1]])
cv2.fillConvexPoly(img, points, 1)
print img
plt.imshow(img, cmap = 'gray')
plt.show()
我的实现
import cv2
import numpy as np
img = cv2.imread('C:/Users/Administrator/Desktop/1551074249341.jpg',1)
points = np.array([[45, 265], [195, 265], [134, 22], [116, 22]])
cv2.fillConvexPoly(img, points,1)
cv2.imshow('a',img)
cv2.imwrite('C:/Users/Administrator/Desktop/mask.jpg',img)
cv2.waitKey(0)
实现结果:
矩形区域掩码
import numpy as np
import cv2
import os
datapath = 'C:/Users/Administrator/Desktop/result_test/test0306/'
outpath = 'C:/Users/Administrator/Desktop/result_test/test0306/'
files = os.listdir(datapath)
for filename in files:
filepath = datapath + filename
image = cv2.imread(filepath)
roi_list = list()
rois = np.array([
[[119, 24], [139, 25], [176, 268], [85, 268]],
])
for roi in rois:
xmin = np.min([coordinates[0] for coordinates in roi])
xmax = np.max([coordinates[0] for coordinates in roi])
ymin = np.min([coordinates[1] for coordinates in roi])
ymax = np.max([coordinates[1] for coordinates in roi])
roi_list.append((xmin, xmax, ymin, ymax))
for roi in roi_list:
result = image
result[roi[2]:roi[3], roi[0]:roi[1]] = 0
cv2.imshow('result', result)
cv2.waitKey(0)