Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
9.0 kB
1
Indexable
Never
import cv2
import numpy as np
import math

cap = cv2.VideoCapture(0)
cap.set(3,640) # ID no.3 is for width
cap.set(4,480) # ID no.4 is for height
cap.set(10,100) #ID no.5 is for brightness'

# the getContour function for detecting the contour in our image
def getContours(img):
    norm_min = 1000000
    cX_min=1000
    cY_min=1000
    cnt_min= None
    contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area>=5000:

            # for detecting the largest contour in all detected contours we used the max function
            #largestcontour = max(contours, key=cv2.contourArea)
            # for detecting the center of each contour we used the following functions
            M = cv2.moments(cnt)
            cX = int(M["m10"] / M["m00"])
            cY = int(M["m01"] / M["m00"])
            norm=math.sqrt(math.pow((cX-960),2)+math.pow((cY-550),2))
            if norm<norm_min:
                norm_min=norm
                cnt_min=cnt
                cX_min=cX
                cY_min=cY

            cv2.drawContours(imgContour, cnt, -1, (255, 255, 0), 1)
            # for determine the 4 parameter of the bounding rectangle to draw it around our area of interest
            # for drawing rectangle around our area of interest we used the rectangle function
        else:
            pass
    x, y, w, h = cv2.boundingRect(cnt_min)
    cv2.putText(imgContour, '.', (x + (w // 2), y + (h // 2)), cv2.FONT_ITALIC, 1, (255, 0, 255), 2)
    #cv2.putText(imgContour, ".", (cX_min, cY_min),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 255), 2)
    print('Module Center= ', ((x + (w // 2), y + (h // 2) + 10)))  # center of each contour
    cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 255), 2)
    #print('contour center 2', cX_min, cY_min)



def empty (a):
    pass

# The name and the size of our center detection Track bar window
cv2.namedWindow('Module center TrackBars')
cv2.resizeWindow('Module center TrackBars', 650,430)
# The name and the size of our center detection Track bar window
cv2.namedWindow('String angel TrackBars')
cv2.resizeWindow('String angel TrackBars', 650,430)

# create Trackbar function to create a track bar
cv2.createTrackbar('Hue Min', 'Module center TrackBars',0, 179, empty ) #Max value of Hue in OpenCV is 179
cv2.createTrackbar('Hue Max', 'Module center TrackBars',179, 179, empty )
cv2.createTrackbar('Sat Min', 'Module center TrackBars',0, 255, empty )
cv2.createTrackbar('Sat Max', 'Module center TrackBars',255, 255, empty )
cv2.createTrackbar('Val Min', 'Module center TrackBars',0, 255, empty )
cv2.createTrackbar('Val Max', 'Module center TrackBars',255, 255, empty )
cv2.createTrackbar('Can Min', 'Module center TrackBars',0, 255, empty )
cv2.createTrackbar('Can Max', 'Module center TrackBars',255, 255, empty )

# create Trackbar function to create a track bar
cv2.createTrackbar('Hue Min', 'String angel TrackBars',0, 179, empty ) #Max value of Hue in OpenCV is 179
cv2.createTrackbar('Hue Max', 'String angel TrackBars',179, 179, empty )
cv2.createTrackbar('Sat Min', 'String angel TrackBars',0, 255, empty )
cv2.createTrackbar('Sat Max', 'String angel TrackBars',255, 255, empty )
cv2.createTrackbar('Val Min', 'String angel TrackBars',0, 255, empty )
cv2.createTrackbar('Val Max', 'String angel TrackBars',255, 255, empty )
cv2.createTrackbar('Can Min', 'String angel TrackBars',0, 255, empty )
cv2.createTrackbar('Can Max', 'String angel TrackBars',255, 255, empty )

# Stacking function for stacking images together
def stackImages(imgArray,scale,lables=[]):
    sizeW= imgArray[0][0].shape[1]
    sizeH = imgArray[0][0].shape[0]
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range ( 0, rows):
            for y in range(0, cols):
                imgArray[x][y] = cv2.resize(imgArray[x][y], (sizeW, sizeH), 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])
            hor_con[x] = np.concatenate(imgArray[x])
        ver = np.vstack(hor)
        ver_con = np.concatenate(hor)
    else:
        for x in range(0, rows):
            imgArray[x] = cv2.resize(imgArray[x], (sizeW, sizeH), None, scale, scale)
            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
        hor= np.hstack(imgArray)
        hor_con= np.concatenate(imgArray)
        ver = hor
    if len(lables) != 0:
        eachImgWidth= int(ver.shape[1] / cols)
        eachImgHeight = int(ver.shape[0] / rows)
        print(eachImgHeight)
        for d in range(0, rows):
            for c in range (0,cols):
                cv2.rectangle(ver,(c*eachImgWidth,eachImgHeight*d),(c*eachImgWidth+len(lables[d][c])*13+27,30+eachImgHeight*d),(255,255,255),cv2.FILLED)
                cv2.putText(ver,lables[d][c],(eachImgWidth*c+10,eachImgHeight*d+20),cv2.FONT_HERSHEY_COMPLEX,0.7,(255,0,255),2)
    return ver

while True:
    success, img = cap.read()
    # imgContour is a copy from our original image
    imgContour = img.copy()



# for extracting a certain value of the trace bar we added the getTrackbarpos Function
    h_min = cv2.getTrackbarPos('Hue Min','Module center TrackBars')
    h_max = cv2.getTrackbarPos('Hue Max', 'Module center TrackBars')
    s_min = cv2.getTrackbarPos('Sat Min', 'Module center TrackBars')
    s_max = cv2.getTrackbarPos('Sat Max', 'Module center TrackBars')
    v_min = cv2.getTrackbarPos('Val Min', 'Module center TrackBars')
    v_max = cv2.getTrackbarPos('Val Max', 'Module center TrackBars')
    C_min = cv2.getTrackbarPos('Can Min', 'Module center TrackBars')
    C_max = cv2.getTrackbarPos('Can Max', 'Module center TrackBars')

    # for extracting a certain value of the trace bar we added the getTrackbarpos Function
    hue_min = cv2.getTrackbarPos('Hue Min', 'String angel TrackBars')
    hue_max = cv2.getTrackbarPos('Hue Max', 'String angel TrackBars')
    sat_min = cv2.getTrackbarPos('Sat Min', 'String angel TrackBars')
    sat_max = cv2.getTrackbarPos('Sat Max', 'String angel TrackBars')
    val_min = cv2.getTrackbarPos('Val Min', 'String angel TrackBars')
    val_max = cv2.getTrackbarPos('Val Max', 'String angel TrackBars')
    Cat_min = cv2.getTrackbarPos('Can Min', 'String angel TrackBars')
    Cat_max = cv2.getTrackbarPos('Can Max', 'String angel TrackBars')


# for creating a mask we need to creat a numpy array to put them in the inRange function (for module center)
    lower = np.array([h_min,s_min,v_min])
    upper = np.array([h_max,s_max,v_max])
    # for creating a mask we need to creat a numpy array to put them in the inRange function (for module center)
    lower_2 = np.array([hue_min, sat_min, val_min])
    upper_2 = np.array([hue_max, sat_max, val_max])

# Img - Blur - HSV - Mask - imgResult by comparing our original image with the mask
    imgBlur = cv2.GaussianBlur(img, (3, 3), 0.5)
    imgHSV = cv2.cvtColor(imgBlur,cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(imgHSV, lower, upper)
    mask_2 = cv2.inRange(imgHSV, lower_2, upper_2)
    imgResult = cv2.bitwise_and(img, img, mask=mask)
    imgResult_2 = cv2.bitwise_and(img, img, mask=mask_2)
    imgCanny = cv2.Canny(mask, C_min, C_max)

# Hough line function for detection the lines in our image
    lines = cv2.HoughLines(mask_2, 1, np.pi / 180, 200)
    for rho, theta in lines[0]:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 1000 * (-b))
        y1 = int(y0 + 1000 * (a))
        x2 = int(x0 - 1000 * (-b))
        y2 = int(y0 - 1000 * (a))

        cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
        print('String angle in radians=',theta)
        print('String angle in degrees=', math.degrees(theta))
    #cv2.imwrite('pv.png', imgResult_2)

# Just as extra information to see how canny function react to detect the edges in our imgResult photo
    getContours(img)


    cv2.imshow('Original', img)
    #cv2.imshow('Blur', imgBlur)
    #cv2.imshow('Gray', imgGray)
    cv2.imshow('Canny', imgCanny)
    #cv2.imshow('Blank', imgBlank)
    cv2.imshow('imgcontour',imgContour)
    cv2.imshow('HSV',imgHSV)
    cv2.imshow('Result', imgResult)
    cv2.imshow('mask',mask)

    #StackedImages = stackImages(([img, imgResult_2, mask_2 ], [imgContour, imgResult, mask]), 5)
    #cv2.imshow('stackedimages', StackedImages)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break