tomfriwel
tomfriwel

Reputation: 2635

OpenCV - How to split a image to two regions by a oblique line?

I'm using HoughLinesP to detect lines in a image. The result is a oblique line. I want to do some operations(erode and dilate) on the region under the line.

So I want ask how to split the image by this line into two regions(region0 and region1) or deal the region1 without split image.

For example, the image size is 200*100, and line is (0, 50, 200, 75).

If the line is horizontal or vertical, I can use image[y:y+h, x:x+w] to crop the image when I get the rect(x, y, w, h) of crop area. But I have no idea for oblique line.

Sample Image

Upvotes: 2

Views: 3696

Answers (1)

Kinght 金
Kinght 金

Reputation: 18341

You can use slice-op to get an rectangle, and mask-op to get non-rectangle like this.

enter image description here

Basic steps are:

  1. define an empty image.
  2. define the corner points.
  3. drawContours in the empty image (with filled)
  4. do mask-op

My Python3-OpenCV3.3 Code:

## Step 1-3: drawContours in empty image
mask = np.zeros((100,200), np.uint8)
pts = np.array([[0,0],[0,50],[199,75],[199,0]])
_=cv2.drawContours(mask, np.int32([pts]),0, 255, -1)

## Step 4: do mask-op
img1 = img.copy()
img2 = img.copy()
img1[mask==0] = 0
img2[mask>0] = 0

## Write
cv2.imwrite("mask.png", mask)
cv2.imwrite("img1.png", img1)
cv2.imwrite("img2.png", img2)

Here are images and the result:

src and mask:

src mask

results:

res1 res2

Upvotes: 3

Related Questions