图像ROI与ROI操作
图像ROI解释:
图像的ROI(region of interest)是指图像中感兴趣区域、在OpenCV中图像设置图像ROI区域,实现只对ROI区域操作。
矩形ROI区域提取
矩形ROI区域copy
不规则ROI区域
import cv2 as cv
import numpy as np
src = cv.imread("C:/Users/qqxd/Desktop/opencvcode/images/test.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
h, w = src.shape[:2]
print(h,w)
roi = src[20:230,130:300,:]
cv.imshow("roi", roi)
# copy ROI
image = np.copy(roi)
# modify ROI
#通过切片操作对图像的通道进行处理
#b通道为0
roi[:, :,0 ] = 0
#g通道为0
# roi[:, :,1 ] = 0
# r通道为0
# roi[:, :,2] = 0
cv.imshow("result", src)
src2 = cv.imread("C:/Users/qqxd/Desktop/opencvcode/images/greenback.png");
cv.imshow("src2", src2)
hsv = cv.cvtColor(src2, cv.COLOR_BGR2HSV)
mask = cv.inRange(hsv, (35, 43, 46), (99, 255, 255))
mask = cv.bitwise_not(mask)
person = cv.bitwise_and(src2, src2,mask=mask)
cv.imshow("person",person)
result = np.zeros(src2.shape, src2.dtype)
result[:,:,0] = 255
mask = cv.bitwise_not(mask)
cv.imshow("mask",mask)
dst = cv.bitwise_or(person, result,mask = mask)
dst = cv.add(dst, person)
cv.imshow("dst",dst)
#从而完成换底操作
cv.waitKey(0)
cv.destroyAllWindows()
#include
#include
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src = imread("C:/Users/qqxd/Desktop/opencvcode/images/test.png");
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
int h = src.rows;
int w = src.cols;
// 获取ROI
Rect rect(130, 20, 300-130, 230-20);
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("C:/Users/qqxd/Desktop/opencvcode/images/greenback.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;
}