[英]Detect if there is gray color in image by opencv Python
我是 cv2 庫的新手,我想制作一個程序來實時檢測圖像中是否有灰色。 直到現在我拿了一個代碼來實時顯示屏幕
import numpy as np
import cv2
import pyautogui
from mss import mss
from PIL import Image
mon = {'top': 268, 'left': 968, 'width': 931, 'height': 599}
sct = mss()
while 1:
sct.get_pixels(mon)
img = Image.frombytes('RGB', (sct.width, sct.height), sct.image)
cv2.imshow('test', np.array(img))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
但我不知道如何檢測屏幕上是否出現灰色(其他問題是關於是否所有圖片都是灰色的,而不是屏幕上是否出現灰色)
更好的方法是將顏色空間更改為 HSV 並找到顏色的色調值范圍。
下面的代碼來自OpenCV 官方網站,用於檢測藍色對象
import cv2 as cv
import numpy as np
cap = cv.VideoCapture(0)
while(1):
# Take each frame
_, frame = cap.read()
# Convert BGR to HSV
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
mask = cv.inRange(hsv, lower_blue, upper_blue)
# Bitwise-AND mask and original image
res = cv.bitwise_and(frame,frame, mask= mask)
cv.imshow('frame',frame)
cv.imshow('mask',mask)
cv.imshow('res',res)
k = cv.waitKey(5) & 0xFF
if k == 27:
break
cv.destroyAllWindows()
用於實時屏幕灰度檢測
范圍將在 HSV 是
lower_blue = np.array([0,0,0]) upper_blue = np.array([255,10,255])
在 HSV/HSL 色彩空間中,灰色像素的特點是飽和度非常接近於零。 然后 Value 通道會告訴你它們實際上從黑色到白色的比例有多遠,低亮度/值是深灰色,而高亮度/值意味着淺灰色。
所以對於灰色,你的代碼如下
import numpy as np
from PIL import Image
from mss import mss
import cv2 as cv
import cv2
mon = {'top': 268, 'left': 968, 'width': 931, 'height': 599}
sct = mss()
while (1):
# Take each
sct.get_pixels(mon)
img = Image.frombytes('RGB', (sct.width, sct.height), sct.image)
img = np.array(img)
# Convert RGB to HSV
hsv = cv.cvtColor(img, cv.COLOR_RGB2HSV)
# define range of gray color in HSV
lower_gray = np.array([0, 0, 0])
upper_gray = np.array([255, 10, 255])
# Threshold the HSV image to get only gray colors
mask = cv.inRange(hsv, lower_gray, upper_gray)
# Bitwise-AND mask and original image
res = cv.bitwise_and(img, img, mask=mask)
cv.imshow('original', img)
cv.imshow('mask', mask)
cv.imshow('res', res)
k = cv.waitKey(5) & 0xFF
if k == 27:
break
cv.destroyAllWindows()
以下代碼可用於靜態圖像
import cv2
import numpy as np
image_path ="trail.jpg"
img = cv2.imread(image_path)
# Convert BGR to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# define range of gray color in HSV
lower_gray = np.array([0,0,0])
upper_gray = np.array([255,10,255])
# Threshold the HSV image to get only gray colors
mask = cv2.inRange(hsv, lower_gray, upper_gray)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(img,img, mask= mask)
cv2.imwrite("output.png",res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.