Esempio n. 1
0
def scan():
    """
    Open up the webcam and scans the 9 regions in the center
    and show a preview.

    After hitting the space bar to confirm, the block below the
    current stickers shows the current state that you have.
    This is show every user can see what the computer took as input.

    :returns: dictionary
    """

    sides   = {}                            # collection of scanned sides
    preview = ['white','white','white',     # default starting preview sticker colors
               'white','white','white',
               'white','white','white']
    state   = [0,0,0,                       # current sticker colors
               0,0,0,
               0,0,0]

    defaultcal = {                          # default color calibration
                'white':[[179,30,255],[0,0,0]],
                'green':[[102,255,184],[63,85,39]],
                'red':[[172,255,147],[13,165,86]],
                'orange':[[172,255,255],[7,136,148]],
                'yellow':[[43,172,235],[23,20,52]],
                'blue':[[118,255,194],[89,178,51]]
                }

    colorcal  = {}                          # color calibration dictionary
    color = ['white', 'green', 'red', 'orange', 'yellow', 'blue']  # list of valid colors            
    
    cv2.namedWindow('default',0)
    # create trackbars here
    cv2.createTrackbar('H Upper',"default",defaultcal[color[len(colorcal)]][0][0],179, empty_callback)
    cv2.createTrackbar('H Lower',"default",defaultcal[color[len(colorcal)]][0][1],179, empty_callback)

    # Remember that the range for S and V are not 0 to 179
    # make four more trackbars for ('S Upper', 'S Lower', 'V Upper', 'V Lower')
    # Note you should use these trackbar names to make other parts of the code run properly


    colorcal = defaultcal

    ##################################################
    # Task 1: you can insert out of the loop code here
    ##################################################



    while cameratesting:
        '''
        Here we want to make sure things are working and learn about how to use some openCV functions
        Your code here
        '''
        #task 1.2 preview a camera window
        #task 1.3 draw a rectangle
        #task 1.4 make a slider
        #task 1.5 add text
        #task 1.6 make a mask based on hsv
        #task 1.7 display the masked image


    while not cameratesting:
        _, frame = None # your code here
        hsv = None      # your code here
        key = None      # your code here

        # init certain stickers.
        draw_detector_stickers(frame)
        draw_recorded_stickers(frame, preview)

        for index,(x,y) in enumerate(detector_stickers):
            roi          = hsv[y:y+32, x:x+32]              # extracts hsv values within sticker
            avg_hsv      = ColorDetector.median_hsv(roi)    # filters the hsv values into one hsv
            color_name   = ColorDetector.get_color_name(avg_hsv,colorcal) # extracts the color based on hsv
            state[index] = color_name                       # stores the color 

            # update when space bar is pressed.
            if key == 32:
                preview = list(state)
                draw_recorded_stickers(frame, state)         # draw the saved colors on the preview
                face = color_to_notation(state[4])          # convert the color to notation of the middle sticker and label this as the face
                notation = [color_to_notation(color) for color in state] # convert all colors to notation
                sides[face] = notation                      # update the face in the sides dictionary

        # show the new stickers
        draw_current_stickers(frame, state)                 # draw live sampling of face colors

        # append amount of scanned sides
        text = 'scanned sides: {}/6'.format(len(sides))
        cv2.putText(frame, text, (20, 460), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
        
        # indicate the scanning instruction
        textInstruction = 'scan and rotate the cube with white on the top and green on the front (towards camera)'
        textInstruction2 = 'the color of center brick is used as the side identifier (since the center brick does not move)'
        textInstruction3 = 'you can scan as many times as you want'
        textInstruction4 = 'the program will overwrite the old scan when same side is detected'
        cv2.putText(frame, textInstruction, (20, 600), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
        cv2.putText(frame, textInstruction2, (20, 620), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
        cv2.putText(frame, textInstruction3, (20, 640), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
        cv2.putText(frame, textInstruction4, (20, 660), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)

        # quit on escape.
        if key == 27:
            break

        # show result
        cv2.imshow("default", frame)

        if key == 99: 
            colorcal = {}   
            while len(colorcal) < 6:
                _, frame = cam.read()
                
                
                hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
                key = cv2.waitKey(10) & 0xff

                # hue upper lower
                hu = cv2.getTrackbarPos('H Upper','default')
                hl = cv2.getTrackbarPos('H Lower','default')
                # saturation upper lower
                su = None # yourcode here
                sl = None # yourcode here
                # value upper lower
                vu = None # yourcode here
                vl = None # yourcode here

                if color[len(colorcal)] == 'red' or color[len(colorcal)] == 'orange':
                    lower_hsv = np.array([0,sl,vl])
                    upper_hsv = np.array([hl,su,vu])
                    mask1 = cv2.inRange(hsv, lower_hsv, upper_hsv)
                    lower_hsv = np.array([hu,sl,vl])
                    upper_hsv = np.array([179,su,vu])
                    mask2 = cv2.inRange(hsv, lower_hsv, upper_hsv)
                    mask = cv2.bitwise_or(mask1, mask2)
                    res = cv2.bitwise_and(frame,frame, mask= mask)
                    lower_hsv = np.array([hl,sl,vl])
                    upper_hsv = np.array([hu,su,vu])
                else:
                    lower_hsv = np.array([hl,sl,vl])
                    upper_hsv = np.array([hu,su,vu])
                    
                    # Task 3
                    mask = None # your code here
                    res = None # your code here
                
                if key == 32:
                    defaultcal[color[len(colorcal)]] = [upper_hsv,lower_hsv]
                    colorcal[color[len(colorcal)]] = [upper_hsv,lower_hsv]

                    if(len(colorcal) < 6):
                        cv2.setTrackbarPos('H Upper','default',defaultcal[color[len(colorcal)]][0][0])
                        cv2.setTrackbarPos('S Upper','default',defaultcal[color[len(colorcal)]][0][1])
                        cv2.setTrackbarPos('V Upper','default',defaultcal[color[len(colorcal)]][0][2])
                        cv2.setTrackbarPos('H Lower','default',defaultcal[color[len(colorcal)]][1][0])
                        cv2.setTrackbarPos('S Lower','default',defaultcal[color[len(colorcal)]][1][1])
                        cv2.setTrackbarPos('V Lower','default',defaultcal[color[len(colorcal)]][1][2])

                if(len(colorcal) < 6):
                    text = 'calibrating {}'.format(color[len(colorcal)])
                cv2.putText(res, text, (20, 460), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)

                cv2.imshow("default", res)
                # quit on escape key.
                if key == 27:
                    break

    cam.release()
    cv2.destroyAllWindows()
    return sides if len(sides) == 6 else False