我正在使用Raspberry Pi
它的相机来执行一些图像处理算法。因此,我正在对捕获的流的连续帧执行背景减法,并尝试查找图像中是否存在任何对象,如果是,则打印出它的区域。该算法按预期工作正常,但存在问题。
使用的阈值函数会cv2.THRESH_OTSU
在没有物体存在时产生颗粒状图像,即背景和前景图像相同。然而,当前景图像中存在对象时,这些噪声/颗粒会消失。这些如下 -
如您所见,如果图像几乎相同,则存在噪点,如果在帧中引入任何对象,则噪点消失。
我尝试了以下方法来消除噪音,但没有奏效。
尝试仅使用
cv2.THRESH_BINARY
/cv2.THRESH_BINARY_INV
不使用 Otsu 二值化。我尝试增加捕获图像的亮度/对比度/饱和度,以查看性能是否变化,但没有变化。
我试图增加/减少步骤之前的
erosion
/数量,但这也没有做出任何改变。dilation
Thresholding
这是我的代码 -
from time import sleep
from picamera import PiCamera
from picamera.array import PiRGBArray
import cv2,os
import numpy as np
import threading
def imageSubtract(img):
bilateral_filtered_image = cv2.bilateralFilter(img, 9, 170, 170)
bilateral_filtered_image = cv2.cvtColor(bilateral_filtered_image,cv2.COLOR_BGR2GRAY)
return bilateral_filtered_image
def imageProcessing():
camera = PiCamera()
camera.resolution = (512,512)
camera.awb_mode="fluorescent"
camera.iso = 800
camera.contrast=33
camera.brightness=75
camera.sharpness=100
rawCapture = PiRGBArray(camera, size=(512, 512))
first_time=0
frame_buffer=0
counter=0
camera.start_preview()
sleep(2)
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
if first_time==0:
rawCapture.truncate(0)
if frame_buffer<10:
print("Frame rejected -",str(frame_buffer))
frame_buffer+=1
continue
os.system("clear")
refImg=frame.array
refThresh=imageSubtract(refImg)
first_time=1
image = frame.array
cv2.imshow("Foreground", image)
key = cv2.waitKey(1)
rawCapture.truncate(0)
newThresh=imageSubtract(image)
diff=cv2.absdiff(refThresh,newThresh)
kernel = np.ones((5,5),np.uint8)
diff=cv2.dilate(diff,kernel,iterations = 3)
cv2.imshow("Background",refImg)
_, thresholded = cv2.threshold(diff, 0 , 255, cv2.THRESH_BINARY +cv2.THRESH_OTSU)
_, contours, _= cv2.findContours(thresholded,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
try:
c=max(contours,key=cv2.contourArea)
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(thresholded,(x,y),(x+w,y+h),(125,125,125),2)
if cv2.contourArea(c)>500:
print("Object detected with area = ",cv2.contourArea(c))
cv2.imshow("Threshold",thresholded)
if key == ord('q'):
camera.close()
cv2.destroyAllWindows()
break
except Exception as e:
pass
if __name__ == "__main__" :
imageProcessing()
当背景和前景图像相同时,请帮我消除噪音。
谢谢你 !