Как передать свойство объекта, полученное из функции, в одно и то же имя переменной для обработки трехцветного изображения? - PullRequest
0 голосов
/ 21 октября 2019

При обработке цветного изображения для приложения виртуальной мыши мне необходимо определить цвет красного, зеленого и синего перед выполнением кода моей основной функции мыши. Сначала пользователь получает возможность 3 раза откалибровать цветовой указатель для цикла, введя свои значения HSV через созданную мною трекбар. Затем значения помещаются в 3 объекта, построенных классом Color () для определенных свойств цветов. Теперь проблема заключается в том, что переменная, собранная и сохраненная в объекте, не может быть присвоена тому же имени переменной, как lowerBound и upperBound, которые необходимы дляиспользоваться в моей функции preprocess (). Если я вместо этого передам другое имя переменной, например lowerBoundRed, моя функция не будет работать, поскольку пользовательские значения в нее не вставляются. Как мне решить эту проблему? Существуют ли альтернативы для функции, например, передача в нее аргументов, которые будут вводить правильные значения для lowerBound и upperBound в соответствии с цветом. В моем коде нет ошибок, только предупреждение, отображаемое в части ### основного кода.

class Colour():
    def __init__(self,lowerBound,upperBound):
        self.lowerBound=lowerBound
        self.upperBound=upperBound

def getTrackbar(name):
    global hmin,hmax,smin,smax,vmin,vmax
    hmin =cv2.getTrackbarPos('HMin', name)
    hmax = cv2.getTrackbarPos('HMax', name)
    smin =cv2.getTrackbarPos('SMin', name)
    smax = cv2.getTrackbarPos('SMax', name)
    vmin =cv2.getTrackbarPos('VMin', name)
    vmax = cv2.getTrackbarPos('VMax', name)

def preprocess():
    global lowerBound,upperBound,maskFinal

    lowerBound = np.array([hmin, smin, vmin])
    upperBound = np.array([hmax, smax, vmax])

    #creating a mask for colors according to input values from user
    mask = cv2.inRange(imgHSV, lowerBound, upperBound)

    # morphology
    maskOpen = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernelOpen)
    maskClose = cv2.morphologyEx(maskOpen, cv2.MORPH_CLOSE, kernelClose)
    maskFinal = maskClose
global t,lowerBound0,lowerBound1,lowerBound2,upperBound0,upperBound1,upperBound2,Red,GreenBlue
for t in range(3):
    cv2.namedWindow('Hue Calibration {0}'.format(t + 1))
    trackbar('Hue Calibration {0}'.format(t + 1))
    while True:
        ret, img=cam.read() # capture frame by frame
        img=cv2.resize(img,(camx,camy)) # resize the image captured
        imgHSV= cv2.cvtColor(img,cv2.COLOR_BGR2HSV) # convert BGR to HSV
        getTrackbar('Hue Calibration {0}'.format(t+1)) # function not shown here
        preprocess()
        if t == 0:
            Red=Colour(lowerBound,upperBound)      ##Class object created here
        if t == 1:
            Green = Colour(lowerBound, upperBound) 
        if t == 2:
            Blue = Colour(lowerBound,upperBound)
while True:

    # capture frame by frame
    ret, img = cam.read()
    # resize the image captured
    img = cv2.resize(img, (camx, camy))
    # convert BGR to HSV
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    cv2.rectangle(img, (80, 60), (240, 180), (0, 255, 255), 2)  # 320x,240y

    lowerBound = Red.lowerBound
    upperBound = Red.upperBound
    preprocess()
    maskFinal0=maskFinal

    ### Warning highlighted and stated on the lowerBound and upperBound variable 
    lowerBound = Green.lowerBound
    upperBound = Green.upperBound
    preprocess()
    maskFinal1=maskFinal

    ### Warning highlighted and stated on the lowerBound and upperBound variable
    lowerBound = Blue.upperBound
    upperBound = Blue.upperBound
    preprocess()
    maskFinal2=maskFinal

    # create the combined Mask 
    maskFinal=maskFinal0+maskFinal1+maskFinal2


    # function of mouse written here,not shown

    cv2.namedWindow("cam",cv2.WINDOW_NORMAL)
    cv2.imshow("cam", img)
    cv2.imshow("maskFinal", maskFinal)
    cv2.imshow("maskFinal0",maskFinal0)
    cv2.imshow("maskFinal1", maskFinal1)
    cv2.imshow("maskFinal2", maskFinal2)
    key = cv2.waitKey(1) & 0xFF
    if key == 27:
        cam.release()
        cv2.destroyAllWindows()
        break

The expected output will be in the 
maskFinal0- detection of Red are seen as white color while others are black
maskFinal1- detection of Green are seen as white color while others are black
maskFinal2- detection of Blue are seen as white color while others are black
maskFinal -the detection of Red, Green and Blue colours are seen as white color while the others are black.

The obtained results are all the mask results are the same , and only blue is detected,meaning somehow in my opinion only the blue HSV values are being inputted into the function preprocess() only.

The warning that are shown on the ### part in the main code is "Redeclared 'lowerBound' and 'upperBound'  defined above without usage". Inspection info:This inspection detects unconditional redeclarations of names without being used in between.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...