OpenCV改变矩形的RGB参数

OpenCV change RGB parameters in rectangle

我有4分。例如...

A(1;1)
B(2;5)
C(4;4)
D(3;2)

如何更改此矩形中的 RGB 参数(对于所有像素)?

像这样:

double[] data = mat.get(x, y);
data[0] = data[0]+30;
data[1] = data[1]+20;
data[2] = data[2]+10;
mat.put(x, y, data);

根据以下评论编辑答案:

这是 OpenCV C++ 代码,但您可以轻松地将其移植到 JAVA。此外,我的代码假定这些点始终代表一个矩形。

// read image
Mat image=imread("image.jpg",-1);

// region of interest, shape=rectangle
Point p1(50,50), p2(100,80);
Rect roi(p1.x,p1.y,p2.x,p2.y);

// vector hold channels
std::vector<Mat> channels(3);

// split original image to bgr channels
cv::split(image, channels);

// Mat to hold ROI
Mat extractedRoi;

//For channel B
extractedRoi = channels.at(0)(roi);
extractedRoi += 30;

//For channel G
extractedRoi = channels.at(1)(roi);
extractedRoi += 20;

//For channel R
extractedRoi = channels.at(2)(roi);
extractedRoi += 10;

// merge channels back together
cv::merge(channels, image);

Edit2:更快的方法。

Mat image=imread("/home/haseebullah/Pictures/S1.jpg",-1);

Point p1(50,50), p2(100,80);
Rect roi(p1.x,p1.y,p2.x,p2.y);

Mat extractedRoi;

extractedRoi = image(roi);

Scalar constants(30,20,10);

extractedRoi += constants

尝试类似的方法来实现 Dan Mašek 评论中描述的方法:

...
Bitmap sourceBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.<your_image>);
Mat sourceMat = new Mat(sourceBitmap.getWidth(), sourceBitmap.getHeight(), CvType.CV_8UC3);
Utils.bitmapToMat(sourceBitmap, sourceMat);

Mat maskMat = new Mat(sourceBitmap.getWidth(), sourceBitmap.getHeight(), CvType.CV_8UC4);
Mat resultMat = new Mat(sourceBitmap.getWidth(), sourceBitmap.getHeight(), CvType.CV_8UC4);

// create color, which added to sourceMat region (+100 - for red channel)
Scalar color = new Scalar(100, 0, 0, 255);

// or you can try Scalar color = new Scalar(10, 20, 30);  as in your question

Point[] region = new Point[4];

// your coords multiplied by 50 for visualization convenience
region[0] = new Point(50, 50);
region[1] = new Point(100, 250);
region[2] = new Point(200, 200);
region[3] = new Point(150, 100);

List<MatOfPoint> contours = new ArrayList();
MatOfPoint regionMat = new MatOfPoint(region);
contours.add(regionMat);

// create mask    
Imgproc.drawContours(maskMat, contours, 0, color, -1);

// apply mask to source
Core.add(maskMat, sourceMat, resultMat);

// just for visualisation
Bitmap bitmap = Bitmap.createBitmap(sourceMat.cols(), sourceMat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(resultMat, bitmap);

<your_ImageView>.setImageBitmap(bitmap);
...

注意!这只是屏蔽的例子,没有优化。