I am trying to perform pixel by pixel operation to threshold the frames from live camera but it shows Not Responding. I think its because of for loops used for comparing each pixel. It would really help if there's an alternative for thresholding images based on specific conditions. Below is the code for better understanding :
import cv2
import numpy as np
import imutils
import time
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help="path to the video file")
args = vars(ap.parse_args())
if args.get("video", None) is None:
cap = cv2.VideoCapture(0)
time.sleep(2.0)
else:
cap = cv2.VideoCapture(args["video"])
firstFrame = None
while True:
_,frame = cap.read()
if np.shape(frame) == ():
cap = cv2.VideoCapture(args["video"])
continue
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray,(21,21),0)
if firstFrame is None:
firstFrame = gray
continue
frameDelta = cv2.absdiff(firstFrame, gray)
thresh = cv2.threshold(frameDelta, 25,255,cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations = 2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
if len(cnts) != 0:
c = max(cnts, key = cv2.contourArea)
(x,y,w,h) = cv2.boundingRect(c)
ROI = frame[x:x+w, y:y+h]
(a,b,c) = np.shape(ROI)
if a==0 or b==0 or c==0:
continue
img = ROI
Rule1 = img.copy()
Rule2 = img.copy()
Rule3 = img.copy()
Rule4 = img.copy()
Rule5 = img.copy()
YCrCb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
Y = YCrCb[:,:,0]
Cr = YCrCb[:,:,1]
Cb = YCrCb[:,:,2]
Ym = int(np.mean(Y))
Crm = int(np.mean(Cr))
Cbm = int(np.mean(Cb))
h = img.shape[0]
w = img.shape[1]
for x in range(0,h) :
for y in range(0,w) :
Rule1[x,y] = 255 if Y[x,y] > Cb[x,y] else 0
Rule2[x,y] = 255 if Cr[x,y] > Cb[x,y] else 0
Rule3[x,y] = 255 if abs(int(Cb[x,y])-int(Cr[x,y]))>=70 else 0
Rule4[x,y] = 255 if Y[x,y]>Ym or Cb[x,y]>Cbm or Cr[x,y]>Crm else 0
Rule5[x,y] = 255 if Cb[x,y]<=120 and Cr[x,y]>=150 else 0
FireRegion = cv2.bitwise_and(Rule1,Rule2)
FireRegion = cv2.bitwise_and(FireRegion,Rule3)
FireRegion = cv2.bitwise_and(FireRegion,Rule4)
FireRegion = cv2.bitwise_and(FireRegion,Rule5)
else :
continue
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow("frame",frame)
cv2.imshow("FireRegion",FireRegion)
time.sleep(0.2)
else :
cv2.imshow("frame",frame)
key = cv2.waitKey(1)
if key ==27 :
break