C++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
string image_path = "G:\\photo\\2.jpg";
Mat img = imread(image_path);
std::cout << "size: " << img.size().height << " , " << img.size().width << std::endl;
Mat dst;
Mat roi = Mat::zeros(img.size(), CV_8U);
vector<vector<Point>> contour;
vector<Point> pts;
pts.push_back(Point(30, 45));
pts.push_back(Point(100, 15));
pts.push_back(Point(300, 145));
pts.push_back(Point(330, 240));
pts.push_back(Point(50, 250));
contour.push_back(pts);
drawContours(roi, contour, 0, Scalar::all(255), -1);
img.copyTo(dst, roi);
imshow("roi", roi);
imshow("img", img);
imshow("dst", dst);
imwrite("1.jpg", roi);
roi.release();
img.release();
dst.release();
waitKey(0);
return 0;
}
PYTHON
import cv2
import numpy as np
lsPointsChoose = [(30, 45),(100, 15),(100, 15),(330, 240),(50, 250)]
img = cv2.imread('2.jpg')
mask = np.zeros(img.shape, np.uint8)
pts = np.array([lsPointsChoose], np.int32)
# pts.shape=(4,2)
pts = pts.reshape((-1, 1, 2)) # -1代表剩下的维度自动计算
# reshape 后的 pts.shape=(4。1,2)??
# --------------画多边形---------------------
mask = cv2.polylines(mask, [pts], True, (0, 255, 255))
##-------------填充多边形---------------------
mask2 = cv2.fillPoly(mask, [pts], (255, 255, 255))
cv2.imshow('mask', mask2)
ROI = cv2.bitwise_and(mask2, img)
cv2.imshow('ROI', ROI)
cv2.waitKey(0)