我正在使用Raspberry Pi
和它的相机来执行一些图像处理算法。因此,我在捕获的流的连续帧上执行背景减法,并尝试查找图像中是否存在任何对象,如果是,则打印出它的区域。该算法按预期工作正常,但存在问题。
使用cv2.THRESH_OTSU
的阈值函数在没有物体存在时会产生颗粒状图像,即背景和前景图像相同。然而,当前景图像中存在物体时,这些噪声/颗粒消失。这些如下 -
如您所见,如果图像几乎相同,则会出现噪音,如果框架中有任何物体,噪音就会消失。
我已经尝试过以下方法来消除噪音,但它没有用。
在没有Otsu二元化的情况下仅使用cv2.THRESH_BINARY
/ cv2.THRESH_BINARY_INV
进行了尝试。
我尝试过提高拍摄图像的亮度/对比度/饱和度,看看性能是否有所不同,但没有变化。
我尝试在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()
当背景和前景图像相同时,请帮助我消除噪音。
谢谢!