Python opencv watershed algorithm example, pythonopencv

Source: Internet
Author: User

Python opencv watershed algorithm example, pythonopencv

This article introduces the watershed algorithm example of python opencv and shares it with you as follows:

Target

  1. Use the watershed algorithm to separate tagged Images
  2. Use the cv2.watershed () function ()

Principle:

Gray images can be seen as topological planes. peaks can be seen in areas with high gray values, while valleys can be seen in areas with low gray values. Fill each valley with water of different colors. When the water level rises, the water in different valleys confluence. To prevent the water from confluence in different valleys, a dam is built at the junction. Then continue to fill the water, and then build a dam until the mountain is masked. The built dam is the image segmentation.

This method usually produces a transitional split result because of noise in the image and other factors. To reduce this impact, opencv uses the Mark-based watershed algorithm, which sets the convergence points in the valley and which are not. This is an interactive image segmentation algorithm. We need to apply different expressions to known objects. If an area must be a foreground or object, use a color or grayscale value label to mark it. If it is a background, use other colors for marking, and use 0 for other uncertain parts. Then, the watershed algorithm is used to update the labels for each irrigation. When two tags of different colors meet each other, a dam is built, all the mountain masks are known, and the final boundary object value is-1.

Code:

Split the objects together.

The result after Otsu's binarization is

To remove the white noise in the image. You can use morphological operations and closed operations to remove holes in objects.

The area close to the center of the object is the foreground, the area far away from the object is the background, and the uncertain area is the border.

First, extract the coin area, use the corrosion operation to remove the edge, and the rest is the coin. However, this method is effective when coins are not in contact with each other, but because coins are in contact with each other, another effective method should be used: Distance Transformation plus a suitable threshold value.

Then, you need to find the area where you are not sure whether it is a coin. Expansion is required here. The expansion operation will extend the object boundary to the background. As the border area is removed, you can now know which areas are foreground and background.

If you do not know how to differentiate the remaining regions, use the watershed algorithm. These areas are usually the border between the foreground and the background. The border is obtained from the area where the background is confirmed, minus the area where the foreground is determined.

(Foreground and background)

(The figure above is the result produced after the author's code is used directly, and the foreground is extracted. To demonstrate the uncertain area, the Distance Transformation parameter of the computing foreground is adjusted, makes the middle area uncertain)

Here we use a cv2.distanceTransform function.

This function is used to calculate the approximate distance between all pixels in a 2-value image and the nearest value 0 pixels.

The parameter is

Cv2.distanceTransform (src, distanceType, maskSize [, dst]) → dst # src is the input binary image. DistanceType is used to calculate the distance. It can be DIST_USER = (1 ,//! <User defined distanceDIST_L1 = 1 ,//! <Distance = | x1-x2 | + | y1-y2 | DIST_L2 = 2 ,//! <The simple euclidean distanceDIST_C = 3 ,//! <Distance = max (| x1-x2 |, | y1-y2 |) DIST_L12 = 4 ,//! <L1-L2 metric: distance = 2 (sqrt (1 + x * x/2)-1) DIST_FAIR = 5 ,//! <Distance = c ^ 2 (| x |/c-log (1 + | x |/c), c = 1.3998DIST _ WELSCH = 6 ,//! <Distance = c ^ 2/2 (1-exp (-(x/c) ^ 2), c = 2.9846DIST _ HUBER = 7 //! <Distance = | x | <c? X ^ 2/2: c (| x |-c/2), c = 1.345 # maskSize is the size of the mask, only 0, 3, 5DIST_MASK_3 = 3 ,//! <Mask = 3DIST_MASK_5 = 5 ,//! <Mask = 5DIST_MASK_PRECISE = 0 //! <Mask = 0
Import numpy as npimport cv2from matplotlib import pyplot as pltimg = cv2.imread('21.jpg ') gray = cv2.cvtColor (img, cv2.COLOR _ BGR2GRAY) ret, thresh = cv2.threshold (gray, 0,255, cv2.THRESH _ BINARY_INV + cv2.THRESH _ OTSU) kernel = np. ones (3, 3), np. uint8) opening = cv2.morphologyEx (thresh, cv2.MORPH _ OPEN, kernel, iterations = 2) # sure background areasure_bg = cv2.dilate (opening, kernel, iterations = 3) # expansion # Finding sure foreground areadist_transform = convert (opening, 0.2) ret, sure_fg = cv2.threshold (dist_transform, * dist_transform.max (), 255, 0) # The parameter has been modified, uncertain region appears # Finding unknown regionsure_fg = np. uint8 (sure_fg) unknown = cv2.subtract (sure_bg, sure_fg) # subtract prospect cv2.imshow ('P', sure_fg) cv2.waitKey (0)

Now that you know the background is coins, you can create tags. (The data type is int32 array, which is the same as the original image size ).

For the region that has been determined, that is, the background and foreground, use an integer to mark the area that is not determined with 0. You can use the cv2.connectedComponents () function to implement this function. It will mark the background as 0, and other values as positive integers starting from 1.

However, if the background is marked as 0, the watershed algorithm regards it as the location area, so different integers are used for marking. for uncertain areas, the function is marked as 0.

The result is displayed in a JET color map. Dark blue unknown area, coin area uses different colors. The remaining parts are light blue.

Use watershed Algorithms

Good results

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.