Python影像處理(6):分離土壤與植物,python影像處理

來源:互聯網
上載者:User

Python影像處理(6):分離土壤與植物,python影像處理

快樂蝦

http://blog.csdn.net/lights_joy/

歡迎轉載,但請保留作者資訊


下面嘗試分離圖片中的土壤與植物,目標是取得綠色植物映像,將土壤背景變為黑色。測試映像:


首先使用2g-r-b得到一個灰階圖及其長條圖:


# -*- coding: utf-8 -*- import cv2import numpy as npimport matplotlib.pyplot as plt# 使用2g-r-b分離土壤與背景src = cv2.imread('f:\\tmp\\cotton.jpg')cv2.imshow('src', src)# 轉換為浮點數進行計算fsrc = np.array(src, dtype=np.float32) / 255.0(b,g,r) = cv2.split(fsrc)gray = 2 * g - b - r# 求取最大值和最小值(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray)# 計算長條圖hist = cv2.calcHist([gray], [0], None, [256], [minVal, maxVal])plt.plot(hist)plt.show()cv2.waitKey()

原來在計算長條圖之前都先把它轉換為u8的類型,現在看起來完全是多餘的!只需要給出級數和最大最小值就可以了!


最後得到了2g-r-b的長條圖:



再用OTSU對2g-r-b的灰階圖進行二值化:


# 轉換為u8類型,進行otsu二值化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)

然後就得到了一個很好的二值映像:



以此為掩碼得到彩色的植株映像:


# 得到彩色的映像(b8, g8, r8) = cv2.split(src)color_img = cv2.merge([b8 & bin_img, g8 & bin_img, r8 & bin_img])

看看結果:



基本符合我們的預期。







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.