Python Image Processing (6): separation of soil and plants, python Image Processing
Happy shrimp
Http://blog.csdn.net/lights_joy/
Reprinted, but keep the author information
Next we try to separate the soil and plants in the image. The goal is to get a green plant image and turn the soil background into black. Test image:
First, use 2g-r-b to obtain a grayscale image and Its Histogram:
#-*-Coding: UTF-8-*-import cv2import numpy as npimport matplotlib. pyplot as plt # Use 2g-r-b to separate soil and background src = cv2.imread ('f: \ tmp \ cotton.jpg ') cv2.imshow ('src', src) # convert to a floating point to calculate fsrc = np. array (src, dtype = np. float32)/255.0 (B, g, r) = cv2.split (fsrc) gray = 2 * g-B-r # obtain the maximum and minimum values (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc (gray) # Calculate the histogram hist = cv2.calcHist ([gray], [0], None, [256], [minVal, maxVal]) plt. plot (hist) plt. show () cv2.waitKey ()
Previously, we converted the histogram to the u8 type before calculating the histogram. Now it seems completely redundant! You only need to give the series and the maximum and minimum values!
Finally, the histogram of 2g-r-b is obtained:
Use OTSU to binarization 2g-r-b Grayscale Images:
# Convert to u8 type and perform otsu binarization gray_u8 = np. array (gray-minVal)/(maxVal-minVal) * 255, dtype = np. uint8) (thresh, bin_img) = cv2.threshold (gray_u8,-1.0, 255, cv2.THRESH _ OTSU) cv2.imshow ('bin _ img ', bin_img)
Then we get a good binary image:
Use this as the mask to obtain the color plant image:
# Obtain the color image (b8, g8, r8) = cv2.split (src) color_img = cv2.merge ([b8 & bin_img, g8 & bin_img, r8 & bin_img])
Look at the results:
Basically meets our expectations.