|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import cv2 as cv |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +# first, read the image |
| 6 | +#image = cv.imread('coins.jpg') |
| 7 | +image = cv.imread('四破魚(藍圓鰺)2.jpg') |
| 8 | +cv.imshow('Original image', image) |
| 9 | + |
| 10 | +''' |
| 11 | +part of misc |
| 12 | +''' |
| 13 | +# change image from BGR to grayscale |
| 14 | +gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) |
| 15 | +# apply thresholding to convert the image to binary |
| 16 | +ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU) |
| 17 | +# erode the image |
| 18 | +foreground = cv.erode(thresh, None, iterations = 1) |
| 19 | +# Dilate the image |
| 20 | +backgroundTemp = cv.dilate(thresh, None, iterations = 1) |
| 21 | +# Apply thresholding |
| 22 | +ret, background = cv.threshold(backgroundTemp, 1, 128, 1) |
| 23 | +# Add foreground and background |
| 24 | +marker = cv.add(foreground, background) |
| 25 | + |
| 26 | +''' |
| 27 | +part of canny |
| 28 | +''' |
| 29 | +# apply (Gaussian) filter for canny edge detector preprocessing |
| 30 | +gaussian = cv.GaussianBlur(marker, (5, 5), 0) |
| 31 | +# apply canny edge detection |
| 32 | +canny = cv.Canny(gaussian, 100, 300) |
| 33 | + |
| 34 | +''' |
| 35 | +part of watershed |
| 36 | +''' |
| 37 | +# Finding the contors in the image using chain approximation |
| 38 | +new, contours, hierarchy = cv.findContours(canny, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) |
| 39 | +# converting the marker to float 32 bit |
| 40 | +marker32 = np.int32(marker) |
| 41 | +# Apply watershed algorithm |
| 42 | +cv.watershed(image, marker32) |
| 43 | +# Apply thresholding on the image to convert to binary image |
| 44 | +m = cv.convertScaleAbs(marker32) |
| 45 | +ret, thresh = cv.threshold(m, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU) |
| 46 | +# Invert the thresh |
| 47 | +thresh_inv = cv.bitwise_not(thresh) |
| 48 | +# Bitwise and with the image mask thresh |
| 49 | +res = cv.bitwise_and(image, image, mask = thresh) |
| 50 | +# Bitwise and the image with mask as threshold invert |
| 51 | +res3 = cv.bitwise_and(image, image, mask = thresh_inv) |
| 52 | +# Take the weighted average |
| 53 | +res4 = cv.addWeighted(res, 1, res3, 1, 0) |
| 54 | +# Draw the contours on the image with green color and pixel width is 1 |
| 55 | +final = cv.drawContours(res4, contours, -1, (0, 255, 0), 1) |
| 56 | + |
| 57 | +# Display the image |
| 58 | +cv.imshow("Watershed", final) |
| 59 | +# Wait for key stroke |
| 60 | +cv.waitKey() |
0 commit comments