Zi 字媒體
2017-07-25T20:27:27+00:00
fanfuhan OpenCV 教學016 ~ opencv-016-圖像ROI與ROI操作(簡單使用HSV產生ROI實作 前後景分離/去背)
資料來源: https://fanfuhan.github.io/
https://fanfuhan.github.io/2019/03/28/opencv-016/
GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV
圖像的ROI(region of interest)是指圖像中感興趣區域、在OpenCV中圖像設置圖像ROI區域,實現只對ROI區域操作。
01.矩形ROI區域提取
02.矩形ROI區域copy ~ 拷貝(複製)原圖的部分內容成為一張新圖
03.不規則ROI區域 ~使用BGR2HSV將綠色背景分離,並取前景,最後合成新圖
– ROI區域mask生成
– 像素位and操作
– 提取到ROI區域
– 加背景or操作
– add 背景與ROI區域
C++
#include
#include
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;
}
Python
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()
寫了
5860316篇文章,獲得
23313次喜歡