Python Forum
cv2 and opcua, doesn't like each other
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cv2 and opcua, doesn't like each other
#1
Hi, I've got a problem with my code, I have to stop while loop in 244 line using varible from opcua server. It works, but when i using this method my im show function from cv2 doesn't works, I mean when it is displaying the windows which are displaying are in "Not Responding" status. But when I change condition in IF in 244 line to: if cv2.waitkey(1) & 0xFF == ord('q'). Then it works i mean the captured frames are displaying without any problems. I paste a demo code down bellow.

import cv2
import numpy as np
from opcua import Client, ua

done  = 0
opc_load = 0

# <=========================> Import co-ordinates form coord.txt <=========================>
with open('C:/Users/An-kop/.vscode/Objects_detection/dist/get_position_cap/coord.txt', 'r') as file:
    lines = file.readlines()

# <=========================> Defining OPC UA Server IP <=========================>
client = Client("opc.tcp://localhost:2137")

# <=========================> Set variables based on the read coordinates <=========================>
if len(lines) == 6:
    frameWidth = int(lines[0].split(': ')[1].strip())
    frameHeight = int(lines[1].split(': ')[1].strip())
    top_left_x = int(lines[2].split(': ')[1].strip())
    top_left_y = int(lines[3].split(': ')[1].strip())
    bottom_right_x = int(lines[4].split(': ')[1].strip())
    bottom_right_y = int(lines[5].split(': ')[1].strip())
else:

    print("Plik coord.txt nie zawiera oczekiwanych danych.")

# <=========================> Definint the captured image and its size <=========================>
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, frameWidth)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frameHeight)

def empty(a):
    pass

# <=========================> Defining stack images function <=========================>
def stackImages(scale, imgArray):
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[1]

    if rowsAvailable:

        for x in range(0, rows):

            for y in range(0, cols):

                if imgArray[x][y].shape[:2] == imgArray[0][0].shape[2]:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)

                else:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)

                if len(imgArray[x][y].shape) ==2: imgArray[x][y] = cv2.cvtColor(imgArray[x][y], cv2.COLOR_GRAY2BGR)

        imageBlank = np.zeros((height, width, 3), np.uint8)
        hor = [imageBlank] * rows
        hor_con = [imageBlank] * rows

        for x in range (0,rows):
            hor[x] = np.hstack(imgArray[x])
        ver = np.vstack(hor)

    else:

        for x in range(0, rows):

            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)

            else:
                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None, scale, scale)

            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)

        hor = np.hstack(imgArray)
        ver = hor

    return ver


# <=========================> Defining getting contours function <=========================>
def getContours(img, imgContour):
    global area, approx, areaMin, w2, h2, contours, closed
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    maxArea = 0
    maxContourIndex = -1

    for i, cnt in enumerate(contours):
        area = cv2.contourArea(cnt)
        rect = cv2.minAreaRect(cnt)
        (x2, y2), (w2, h2), angle = rect
        areaMin = cv2.getTrackbarPos("Area", "Params")
        box = cv2.boxPoints(rect)
        box = np.int0(box)

        # cv2.polylines(img, [box], True, (255, 0, 0), 1)

        # print(box)

        if area > areaMin:

            if area > maxArea:
                maxArea = area
                maxContourIndex = i

    if maxContourIndex != -1:
        closed = True
        cnt = contours[maxContourIndex]
        cv2.drawContours(imgContour, [box], -1, (255, 0, 255), 2)
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
        # print(len(approx))
        # print("areafor: ", int(maxArea))
        x, y, w, h = cv2.boundingRect(approx)
        cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 3)

        # cv2.putText(imgContour, "Points: " + str(len(approx)), (x + w + 20, y + 20), cv2.FONT_HERSHEY_COMPLEX, .7,
        #             (0, 255, 0), 2)
        # cv2.putText(imgContour, "Area: " + str(int(maxArea)), (x + w + 20, y + 45), cv2.FONT_HERSHEY_COMPLEX, 0.7,
        #             (0, 255, 0), 2)
    else:
        closed = False

# <=========================> Defining OPC UA operations <=========================>
def read_input_value(node_id):
    client_node = client.get_node(node_id)  # get node
    client_node_value = client_node.get_value()  # read node value
    # print("Value of : " + str(client_node) + ' : ' + str(client_node_value))
    # client.disconnect()
    return str(client_node_value)

def write_value_int(node_id, value):
    client_node = client.get_node(node_id)  # get node
    client_node_value = value
    client_node_dv = ua.DataValue(ua.Variant(client_node_value, ua.VariantType.Int16))
    client_node.set_value(client_node_dv)
    # print("Value of : " + str(client_node) + ' : ' + str(client_node_value))
    # client.disconnect()

def write_value_bool(node_id, value):
    client_node = client.get_node(node_id)  # get node
    client_node_value = value
    client_node_dv = ua.DataValue(ua.Variant(client_node_value, ua.VariantType.Boolean))
    client_node.set_value(client_node_dv)
    # print("Value of : " + str(client_node) + ' : ' + str(client_node_value))
    # client.disconnect()
# <=========================> First defining thresholds <=========================>
cv2.namedWindow("Params")
cv2.resizeWindow("Params", 640, 270)
cv2.createTrackbar("Threshold1", "Params", 255, 255, empty)
cv2.createTrackbar("Threshold2", "Params", 150, 255, empty)
cv2.createTrackbar("Area", "Params", 6000, 10000, empty)
cv2.createTrackbar("W_MIN", "Params", 5, 500, empty)
cv2.createTrackbar("W_MAX", "Params", 5, 500, empty)
cv2.createTrackbar("H_MIN", "Params", 5, 100, empty)
cv2.createTrackbar("H_MAX", "Params", 5, 100, empty)

threshold1 = cv2.getTrackbarPos("Threshold1", "Params")
threshold2 = cv2.getTrackbarPos("Threshold2", "Params")
area = cv2.getTrackbarPos("Area", "Params")
w_min = cv2.getTrackbarPos("W_MIN", "Params")
w_max = cv2.getTrackbarPos("W_MAX", "Params")
h_min = cv2.getTrackbarPos("H_MIN", "Params")
h_max = cv2.getTrackbarPos("H_MAX", "Params")

cv2.destroyAllWindows()

# <=========================> While loop in which are creating parameters window <=========================>
while True:

    cv2.namedWindow("Params")
    cv2.resizeWindow("Params", 640, 270)
    cv2.createTrackbar("Threshold1", "Params", threshold1, 255, empty)
    cv2.createTrackbar("Threshold2", "Params", threshold2, 255, empty)
    cv2.createTrackbar("Area", "Params", area, 10000, empty)
    cv2.createTrackbar("W_MIN", "Params", w_min, 500, empty)
    cv2.createTrackbar("W_MAX", "Params", w_max, 500, empty)
    cv2.createTrackbar("H_MIN", "Params", h_min, 100, empty)
    cv2.createTrackbar("H_MAX", "Params", h_max, 100, empty)

    if done == 0:

# <=========================> Main while loop <=========================>
        while True:
            success, frame = cap.read()
            img = frame[top_left_y:bottom_right_y, top_left_x:bottom_right_x]
            imgContour = img.copy()
            imgBlur = cv2.GaussianBlur(img, (7,7), 1)
            imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
            threshold1 = cv2.getTrackbarPos("Threshold1", "Params")
            threshold2 = cv2.getTrackbarPos("Threshold2", "Params")
            imgCanny = cv2.Canny(imgGray, threshold1, threshold2)
            kernel = np.ones((2, 2))
            imgDil = cv2.dilate(imgCanny, kernel, iterations=1)

            getContours(imgDil, imgContour)
            rImg = cv2.resize(img,(0,0),None,0.7,0.7)
            rImgDil = cv2.resize(imgDil,(0,0),None,0.7,0.7)
            rImgContour = cv2.resize(imgContour,(0,0),None,0.7,0.7)
            imgStack = stackImages(0, ([rImg, rImgDil, rImgContour],))
            cv2.imshow("Result", imgStack)

            print("area: ", (int(area)))
            # print("cval: ", cval)
            

            area = cv2.getTrackbarPos("Area", "Params")
            w_min = cv2.getTrackbarPos("W_MIN", "Params")
            w_max = cv2.getTrackbarPos("W_MAX", "Params")
            h_min = cv2.getTrackbarPos("H_MIN", "Params")
            h_max = cv2.getTrackbarPos("H_MAX", "Params")

            t_w2 = w2
            t_h2 = h2
            # print(closed)
            if t_h2 > t_w2:
                w2 = t_h2
                h2 = t_w2
            else:
                w2 = t_w2
                h2 = t_h2
            print("Szerokośc: ", int(w2))
            print("Wysokość: ", int(h2))
            
            if opc_load == 0:
                while True:
                    if __name__ == "__main__":
                        client = Client("opc.tcp://localhost:2137")
                        try:
                            client.connect()

                            root = client.get_root_node()
                            print("Połączono: Objects root node is: ", root)
                            opc_load = 1
                            break
                        finally:
                            print(opc_load)
                            pass

            check = read_input_value('ns=6;s=::AsGlobalPV:Check')
            if check == 'True':
                    done = 1
                    # cv2.destroyAllWindows()
                    cv2.imwrite("./image/stack.jpg", imgStack)
                    show = cv2.imread('./image/stack.jpg')
                    cv2.destroyAllWindows()
                    
                    break
            else: 
                pass

            # if cv2.waitKey(1) & 0xFF == ord('q'):
            #     done = 1
            #     break
# <=========================> Conditional statements confirming the state of the pallet <=========================>
    while True:
        cv2.imshow("Control", show)
        if closed is True:
            if done == 1 and (int(w2) < 130 and int(h2) < 15):
                print(f"Domknięcie konturu: {closed}")
                print(f"Aktualna szerokość: {w2}")
                print(f"Aktualna wysokość: {h2}")
                print(f"Szerokość badanej powierzchni NIE mieści się w tolerancji: {w_min} - {w_max}")
                print(f"Wysokość badanej powierzchni NIE mieści się w tolerancji: {h_min} - {h_max}")
                confirmation1 = input("Obiektyw kamery może być czymś zakryty, lub zabrudzony, przemyj go i wpisz 'ok'/'nok' w zależności od stanu palety: ")

            elif done == 1 and (int(w2) >= w_min and int(w2) <= w_max) and (int(h2) >= h_min and int(h2) <= h_max):
                print(f"Domknięcie konturu: {closed}")
                print(f"Aktualna szerokość: {w2}")
                print(f"Aktualna wysokość: {h2}")
                print(f"Szerokość badanej powierzchni mieści się w tolerancji: {w_min} - {w_max}")
                print(f"Wysokość badanej poweirzchni mieści się w tolerancj: {h_min} - {h_max}")
                input("Wciśnij ENTER")
                print("ZWROTKA DO STAROWNIKA DAJĄCA SYGNAŁ DO DALSZEJ PRACY")
                done = 0
                break

            elif done == 1 and (int(w2) < w_min or int(w2) > w_max) and (int(h2) < h_min or int(h2) > h_max) and (int(w2) >= 130 and int(h2) >= 15):
                print(f"Domknięcie konturu: {closed}")
                print(f"Aktualna szerokość: {w2}")
                print(f"Aktualna wysokość: {h2}")
                print(f"Szerokość badanej powierzchni NIE mieści się w tolerancji: {w_min} - {w_max}")
                print(f"Wysokość badanej powierzchni NIE mieści się w tolerancji: {h_min} - {h_max}")
                print("ZWROTKA DO STEROWNIKA DO OCZEKIWANIA")
                confirmation1 = input("Paleta podczas następnego ruchu może uszkodzić układ. Wpisz 'ok'/'nok' w zależności od stanu palety: ")
                temp = 1

            elif temp == 0 and done == 1:
                if (int(w2) < w_min or int(w2) > w_max) and (int(h2) >= h_min and int(h2) <= h_max):
                    print(f"Domknięcie konturu: {closed}")
                    print(f"Aktualna szerokość: {w2}")
                    print(f"Aktualna wysokość: {h2}")
                    print(f"Szerokość badanej powierzchni NIE mieści się w tolerancji: {w_min} - {w_max}")
                    print(f"Wysokość badanej powierzchni mieści się w tolerancj: {h_min} - {h_max}")
                    print("ZWROTKA DO STEROWNIKA DO OCZEKIWANIA")
                    confirmation1 = input("Paleta podczas następnego ruchu może uszkodzić układ. Wpisz 'ok'/'nok' w zależności od stanu palety: ")
                    temp = 0

                elif (int(h2) < h_min or int(h2) > h_max) and (int(w2) < w_min or int(w2) > w_max):
                    print(f"Domknięcie konturu: {closed}")
                    print(f"Aktualna szerokość: {w2}")
                    print(f"Aktualna wysokość: {h2}")
                    print(f"Szerokość badanej poweirzchni mieści się w tolerancji: {w_min} - {w_max}")
                    print(f"Wysokość badanej powierzchni NIE mieści się w tolerancji: {h_min} - {h_max}")
                    print("ZWROTKA DO STEROWNIKA DO OCZEKIWANIA")
                    confirmation1 = input("Paleta podczas następnego ruchu może uszkodzić układ. Wpisz 'ok'/'nok' w zależności od stanu palety: ")
                    temp = 0

            if confirmation1 == str('ok'):
                print("ZWROTKA DO STEROWNIKA DAJĄCA SYGNAŁ DO DALSZEJ PRACY")
                cv2.destroyAllWindows()
                done = 0
                break

            elif confirmation1 == str('nok'):
                print("ZWROTKA DO STEROWNIKA DAJĄCA SYGNAŁ DO USUNIĘCIA PALETY")
                cv2.destroyAllWindows()
                done = 0
                break

        else:
            if done == 1 and (int(w2) < 130 and int(h2) < 15):
                print(f"Domknięcie konturu: {closed}")
                print(f"Aktualna szerokość: {w2}")
                print(f"Aktualna wysokość: {h2}")
                print(f"Szerokość badanej powierzchni NIE mieści się w tolerancji: {w_min} - {w_max}")
                print(f"Wysokość badanej powierzchni NIE mieści się w tolerancji: {h_min} - {h_max}")
                confirmation2 = input("Obiektyw kamery może być czymś zakryty, lub zabrudzony, przemyj go i wpisz 'ok'/'nok' w zależności od stanu palety: ")

            elif done == 1 and (int(w2) < w_min or int(w2)) > w_max and ((int(h2) < h_min or int(h2) > h_max)) and (int(w2) >= 130 and int(h2) >= 15):
                print(f"Domknięcie konturu: {closed}")
                print(f"Aktualna szerokość: {w2}")
                print(f"Aktualna wysokość: {h2}")
                print(f"Szerokość badanej powierzchni NIE mieści się w tolerancji: {w_min} - {w_max}")
                print(f"Wysokość badanej powierzchni NIE mieści się w tolerancji: {h_min} - {h_max}")
                input("Wciśnij ENTER")
                print("ZWROTKA DO STEROWNIKA DAJĄCA SYGNAŁ DO USUNIĘCIA PALETY")
                cv2.destroyAllWindows()
                done = 0
                break

            elif done == 1 and (int(w2) >= w_min and int(w2) <= w_max) and (int(h2) >= h_min and int(h2) <= h_max):
                print(f"Domknięcie konturu: {closed}")
                print(f"Aktualna szerokość: {w2}")
                print(f"Aktualna wysokość: {h2}")
                print(f"Szerokość badaniej powierzchni mieście się w tolerancji: {w_min} - {w_max}")
                print(f"Wysokość badanej powierzchni mieści się w tolernacji {h_min} - {h_max}")
                print("ZWROTKA DO STEROWNIKA DO OCZEKIWANIA")
                confirmation2 = input("Paleta podczas następnego ruchu może uszkodzić układ. Wpisz 'ok'/'nok' w zależności od stanu palety: ")

            elif done == 1:
                if (int(w2) < w_min or int(w2) > w_max) and (int(h2) >= h_min and int(h2) <= h_max):
                    print(f"Domknięcie konturu: {closed}")
                    print(f"Aktualna szerokość: {w2}")
                    print(f"Aktualna wysokość: {h2}")
                    print(f"Szerokość badanej powierzchni NIE mieści się w tolerancji: {w_min} - {w_max}")
                    print(f"Wysokość badanej powierzchni mieści się w tolerancji: {h_min} - {h_max}")
                    print("ZWROTKA DO STEROWNIKA DO OCZEKIWANIA")
                    confirmation2 = input("Paleta podczas następnego ruchu może uszkodzić układ. Wpisz 'ok'/'nok' w zależności od stanu palety: ")
                    temp = 0

                elif (int(h2) < h_min or int(h2) > h_max) and (int(w2) < w_min or int(w2) > w_max):
                    print(f"Domknięcie konturu: {closed}")
                    print(f"Aktualna szerokość: {w2}")
                    print(f"Aktualna wysokość: {h2}")
                    print(f"Szerokość badanej powierzchni mieści się w tolerancji: {w_min} - {w_max}")
                    print(f"Wysokość badanej powierzchni NIE mieści się w tolerancji: {h_min} - {h_max}")
                    print("ZWROTKA DO STEROWNIKA DO OCZEKIWANIA")
                    confirmation2 = input("Paleta podczas następnego ruchu może uszkodzić układ. Wpisz 'ok'/'nok' w zależności od stanu palety: ")
                    temp = 0

            if confirmation2 == str('ok'):
                print("ZWROTKA DO STEROWNIKA DAJĄCA SYGNAŁ DO DALSZEJ PRACY")
                cv2.destroyAllWindows()
                done = 0
                break

            elif confirmation2 == str('nok'):
                print("ZWROTKA DO STEROWNIKA DAJĄCA SYGNAŁ DO USUNIĘCIA PALETY")
                cv2.destroyAllWindows()
                done = 0
                break

        cv2.destroyAllWindows()
        done = 0

.py   demo.py (Size: 17.99 KB / Downloads: 47)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020