问题
I have an Image(see below) that is marked by two parallel green lines. This image is read in a OpenCV Mat in C++, the slope of green lines and their distances to the image center are already known.
Now I want to iterate all the pixels in the area between these two green lines. How can i solve this problem? It will be very helpful, if somebody can give me a code example.
Many thanks.
回答1:
The formula for a slope is the following:
y = mx + b
Since you have two of them you should have two slope formulas:
y1 = m1x1 + b1
y2 = m2x2 + b2
m1, m2, b1, b2
should be known.
All you have to do is start at y1 = 0
and y2 = 0
, and iterate between x1
to x2
for each y1 = y2
from top to bottom.
Example code:
for (int y = 0; y < imageHeight; ++y)
{
int x1 = (y - b1) / m1;
int x2 = (y - b2) / m2;
for (int x = x1; x < x2; ++x)
{
// Do something.
}
}
回答2:
you could use LineIterator
take a look at the sample code below
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main( int, char** argv )
{
Mat src;
src = imread( argv[1] );
if( src.empty() )
{
return -1;
}
Point pt1 = Point( (src.cols / 5) + (src.cols / 8), src.rows);
Point pt2 = Point( (src.cols ) - (src.cols / 8), 0);
LineIterator it(src, pt1, pt2, 8);
for(int y = 0; y < it.count; y++, ++it)
{
Point it_pos = it.pos();
for(int x = it_pos.x; x < it_pos.x+(src.cols / 5) & x < src.cols; x++)
{
Vec3b & pixel = src.at<Vec3b>(it_pos.y,x);
pixel = pixel * 1.3;
pixel[0] = 0;
}
}
imshow("result", src );
waitKey(0);
return 0;
}
result images (look edit history to understand changes well):
来源:https://stackoverflow.com/questions/36970099/opencv-how-to-iterate-each-pixel-in-a-specific-area-of-an-image