OpenCV之图像ROI与ROI操作

Posted MachineLP

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenCV之图像ROI与ROI操作相关的知识,希望对你有一定的参考价值。

python代码:

import cv2 as cv
import numpy as np

src = cv.imread("./test.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
h, w = src.shape[:2]

# 获取ROI
cy = h//2
cx = w//2
roi = src[cy-100:cy+100,cx-100:cx+100,:]
cv.imshow("roi", roi)

# copy ROI
image = np.copy(roi)

# modify ROI
roi[:, :, 0] = 0
cv.imshow("result", src)

# modify copy roi
image[:, :, 2] = 0
cv.imshow("result", src)
cv.imshow("copy roi", image)

# example with ROI - generate mask
src2 = cv.imread("./test.png")
cv.imshow("src2", src2)
hsv = cv.cvtColor(src2, cv.COLOR_BGR2HSV)
mask = cv.inRange(hsv, (35, 43, 46), (99, 255, 255))

# extract person ROI
mask = cv.bitwise_not(mask)
person = cv.bitwise_and(src2, src2, mask=mask)

# generate background
result = np.zeros(src2.shape, src2.dtype)
result[:,:,0] = 255

# combine background + person
mask = cv.bitwise_not(mask)
dst = cv.bitwise_or(person, result, mask=mask)
dst = cv.add(dst, person)

cv.imshow("dst", dst)

cv.waitKey(0)
cv.destroyAllWindows()

C++代码:

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
	Mat src = imread("./test.png");
	namedWindow("input", WINDOW_AUTOSIZE);
	imshow("input", src);
	int h = src.rows;
	int w = src.cols;

	// ��ȡROI
	int cy = h / 2;
	int cx = w / 2;
	Rect rect(cx - 100, cy - 100, 200, 200);
	Mat roi = src(rect);
	imshow("roi", roi);

	Mat image = roi.clone();
	// modify ROI
	roi.setTo(Scalar(255, 0, 0));
	imshow("result", src);

	// modify copy roi
	image.setTo(Scalar(0, 0, 255));
	imshow("result", src);
	imshow("copy roi", image);

	// example with ROI - generate mask
	Mat src2 = imread("./test.png");
	imshow("src2", src2);
	Mat hsv, mask;
	cvtColor(src2, hsv, COLOR_BGR2HSV);
	inRange(hsv, Scalar(35, 43, 46), Scalar(99, 255, 255), mask);
	imshow("mask", mask);

	// extract person ROI
	Mat person;
	bitwise_not(mask, mask);
	bitwise_and(src2, src2, person, mask);
	imshow("person", person);

	// generate background
	Mat result = Mat::zeros(src2.size(), src2.type());
	result.setTo(Scalar(255, 0, 0));

	// combine background + person
	Mat dst;
	bitwise_not(mask, mask);
	bitwise_or(person, result, dst, mask);
	add(dst, person, dst);

	imshow("dst", dst);
	waitKey(0);
	return 0;
}

OpenCV学习笔记代码,欢迎follow:

MachineLP/OpenCV-​github.com

以上是关于OpenCV之图像ROI与ROI操作的主要内容,如果未能解决你的问题,请参考以下文章

基于opencv的感兴趣区域ROI的操作

opencv-python基础用法详细代码-图片加载-ROI-边缘滤波-二值化-轮廓提取-膨胀腐蚀等

opencv python:ROI 与 泛洪填充

OpenCV_复制一个或多个ROI图像区域

如何使用 Python 和 OpenCV 裁剪图像中的多个 ROI

opencv 实现 ROI 框选功能