我的目标是阅读植物的图像,然后输出仅显示绿色部分而没有任何其他背景颜色的图片。基本上,我只想从图片中提取叶子部分而不是土壤或其他任何东西。到目前为止,我已经能够读取我的图像并将其更改为绿色,但我的目标是实际提取绿色而不是改变整个绿色。关于我可能做错什么的任何想法?
这是我的代码
import matplotlib.pyplot as plt
import numpy as np
# Read and display picture
originalImage = plt.imread("C:/Users/user/Desktop/Image for detection1.jpg")
imgplot = plt.imshow(originalImage)
# Copy 1st picture and turn into an array
edittedImage = originalImage.copy()
arr = np.asarray(originalImage) # create array for image
lowerGreen = np.array([130,137,10]) # define lower values for green
upperGreen = np.array([220,235,130]) # define higher values for green
for color in arr: # loop through pixels to find the color green
if color >= lowerGreen and <= upperGreen:
print (color) # print the image showing only the green sections
imgplot = plt.imshow(edittedImage)
错误味精: 文件&#34; C:/Users/user/.spyder-py3/extract green.py&#34;,第28行,在 如果颜色&gt; = lowerGreen和颜色&lt; = upperGreen:
ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()
答案 0 :(得分:1)
使用OpenCv(cv2模块),我会这样做:
import cv2 as cv
import numpy as np
img = cv.imread('MyImage.jpg')
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
# range of colors to filter by; you can adjust these parameters to fit your image:
lower_red = np.array([40,50,50])
upper_red = np.array([170,200,180])
# select parts of image in color range
mask = cv.inRange(hsv, lower_red, upper_red)
res = cv.bitwise_and(img,img, mask= mask)
cv.imshow('res',res)
cv.waitKey() & 0xFF