c++/python opencv 获取不规则ROI

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)

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值