opencv-016-图像ROI与ROI操作

知识点

图像的ROI(region of interest)是指图像中感兴趣区域、在OpenCV中图像设置图像ROI区域,实现只对ROI区域操作。

  1. 矩形ROI区域提取
  2. 矩形ROI区域copy
  3. 不规则ROI区域
    • ROI区域mask生成
    • 像素位 and操作
    • 提取到ROI区域
    • 加背景or操作
    • add 背景与ROI区域

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* ROI及相关操作
*/
int main() {
Mat src = imread("../images/test.png");
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);
// 注意:roi 与 src指向同一块内存区域,改变roi,src也会改变
Mat roi = src(rect);
imshow("roi", roi);

// 人物背景图,换背景
// load image
Mat image = imread("../images/boy.jpg");
imshow("input", image);
// generate mask
Mat hsv, mask, mask_not;
cvtColor(image, hsv, COLOR_BGR2HSV);
inRange(hsv, Scalar(35, 43, 46), Scalar(99, 255, 255), mask);
imshow("mask", mask);
// extract person
Mat person;
bitwise_not(mask, mask_not);
imshow("mask_not", mask_not);
bitwise_and(image, image, person, mask_not);
imshow("person", person);
// gengerate background
Mat background = Mat::zeros(image.size(), image.type());
background.setTo(Scalar(255, 0 ,0));
imshow("background", background);
// combine background + person
Mat dst;
bitwise_or(person, background, dst, mask);
add(dst, person, dst);
imshow("dst", dst);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import cv2 as cv
import numpy as np

src = cv.imread("D:/javaopencv/dahlia_4.jpg")
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("D:/javaopencv/tinygreen.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()

结果

代码地址

github