Example #1
0
def main(file_name):
    image = cv2.imread(file_name)
    #plt.imshow(image)
    #plt.show()
    occupied_grids = []
    planned_path = {}

    (winW, winH) = (60, 60)
    obstacles = []
    index = [1, 1]

    #Create a blank image initialized a matrix of 0's
    blank_image = np.zeros((60, 60, 3), np.uint8)

    #Create an array of 100 blank images as size of map is 600*600
    list_images = [[blank_image for i in range(10)] for i in range(10)]
    maze = [[0 for i in range(10)] for i in range(10)]

    #Traversal time
    for (x, y, window) in traversal.sliding_window(image,
                                                   stepSize=60,
                                                   windowSize=(winW, winH)):
        #print(x , end = ' ')
        #print(y)
        if (window.shape[0] != winH or window.shape[1] != winW):
            continue
        #Print index image is our iterator
        clone = image.copy()
        #Format square for opencv
        cv2.rectangle(clone, (x, y), (x + winW, y + winH), (255, 255, 0), 4)
        #Crop the image
        crop_img = image[y:y + winW, x:x + winH]
        #Add it to the array of images
        list_images[index[0] - 1][index[1] - 1] = crop_img.copy()
        #cv2.imshow('win', list_images[index[0] - 1][index[1] - 1])
        #time.sleep(0.25)

        #Print the occupied grids check if its white or not
        average_color_per_row = np.average(crop_img, axis=0)
        average_color = np.average(average_color_per_row, axis=0)
        average_color = np.uint8(average_color)

        #Iterate through the color matrix
        if (any(i <= 240 for i in average_color)):
            maze[index[1] - 1][index[0] - 1] = 1
            #If not majority white
            occupied_grids.append(tuple(index))
        if (any(i <= 20 for i in average_color)):
            obstacles.append(tuple(index))

        cv2.imshow("Window", clone)
        cv2.waitKey(1)
        time.sleep(0.25)

        index[1] = index[1] + 1
        if (index[1] > 10):
            index[0] = index[0] + 1
            index[1] = 1

        #Shortest path
        #Get the list of objects

    list_colored_grids = [n for n in occupied_grids if n not in obstacles]

    for startimage in list_colored_grids:
        key_startimage = startimage
        img1 = list_images[startimage[0] - 1][startimage[1] - 1]
        for grid in [n for n in list_colored_grids if n != startimage]:
            #Next image
            img = list_images[grid[0] - 1][grid[1] - 1]
            #Convert to grayscale
            image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            #Comapre structural similarity
            s = ssim(image, image2)
            #If they are similar perform a star search
            if (s > 0.9):
                result = astarsearch.astar(
                    maze, (startimage[0] - 1, startimage[1] - 1),
                    (grid[0] - 1, grid[1] - 1))
                list2 = []
                for t in result:
                    x, y = t[0], t[1]
                    list2.append(tuple((x + 1, y + 1)))
                    #result = list(list2[1:-1])
                if not result:
                    planned_path[startimage] = list(["No path", [], 0])
                planned_path[startimage] = list(
                    [str(grid), result, len(result) + 1])
    for obj in list_colored_grids:
        if not (obj in planned_path):
            planned_path[obj] = list(["No match", [], 0])
    return occupied_grids, planned_path
def main(image_file):

    # Arrays for storing the occupied grid address and planned path
    occupiedGrids = []
    pathPlanned = {}

    # Loading the image
    image = cv2.imread(image_file)
    imW, imH = 60, 60

    obstacles = []
    index = [1, 1]

    # For path, creating a blank matrix of 0's.
    blank_image = np.zeros((imW, imH, 3), dtype=np.uint8)

    # creating an empty array for 100 blank images
    image_list = [[blank_image for _ in range(10)] for _ in range(10)]

    # creating a list of maze
    maze = [[0 for _ in range(10)] for _ in range(10)]

    for x, y, window in traverse_image.sliding_window(image, stepSize=60, windowSize=(imW, imH)):
        # if the window size does not meet the desired window size, it is ignored
        if window.shape[0] != imW or window.shape[1] != imH:
            continue
        
        # cloning the actual image
        clone = image.copy()
        cv2.rectangle(clone, (x, y), (x+imW, y+imH), (0, 255, 0), 2)
        crop_image = image[x:x+imW, y:y+imH]
        image_list[index[0]-1][index[1]-1] = crop_image.copy()

        # printing occupied grids
        average_color = np.uint8(np.average(np.average(crop_image, axis=0), axis=0))

        # iterating through colour matrix
        # getting occupied grids
        if any(i <= 240 for i in average_color):
            maze[index[0]-1][index[1]-1] = 1
            occupiedGrids.append(tuple(index))
        
        # checking for black colour grids
        if any(i <= 20 for i in average_color):
            # print("Obstacles")
            obstacles.append(tuple(index))
        
        # Showing the iteration
        cv2.imshow("Window", clone)
        cv2.waitKey(1)
        time.sleep(0.025)

        # Iterate for the next one
        index[1] += 1
        if index[1]>10:
            index[0] += 1
            index[1] = 1
        
    # getting object list
    # getting occupied grids without black
    list_coloured_grids = [i for i in occupiedGrids if i not in obstacles]

    for start_image in list_coloured_grids:
        key_start_image = start_image
        
        # starting image
        img1 = image_list[start_image[0]-1][start_image[1]-1]

        for grid in [n for n in list_coloured_grids if n != start_image]:
            #next image
            img = image_list[grid[0]-1][grid[1]-1]
            #convert to grayscale
            image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            #compare structural similarity
            s = ssim(image, image2)
            #if they are similar
            if s > 0.9:
                #perform a star search between both
                result = astarsearch.astar(maze,(start_image[0]-1,start_image[1]-1),(grid[0]-1,grid[1]-1))
                list2=[]
                for t in result:
                    x,y = t[0],t[1]
                    #Contains min path + start_image + endimage
                    list2.append(tuple((x+1,y+1)))
                    #Result contains the minimum path required
                    result = list2

                if not result:	#If no path is found;
                    pathPlanned[start_image] = list(["NO PATH",[], 0])
                
                pathPlanned[start_image] = list([str(grid),result,len(result)])
    
    for obj in list_coloured_grids:
        if  obj not in pathPlanned:	#If no matched object is found;
            pathPlanned[obj] = list(["NO MATCH",[],0])			

    return occupiedGrids, pathPlanned
Example #3
0
def main(image_filename):
    '''
	Returns:
	1 - List of tuples which is the coordinates for occupied grid. 
	2 - Dictionary with information of path. 
	'''

    occupied_grids = []  # List to store coordinates of occupied grid
    planned_path = {
    }  # Dictionary to store information regarding path planning

    # load the image and define the window width and height
    image = cv2.imread(image_filename)
    (winW, winH) = (60, 60)  # Size of individual cropped images

    obstacles = []  # List to store obstacles (black tiles)
    index = [1, 1]
    blank_image = np.zeros((60, 60, 3), np.uint8)
    list_images = [[blank_image for i in xrange(10)]
                   for i in xrange(10)]  #array of list of images
    maze = [[0 for i in xrange(10)] for i in xrange(10)
            ]  #matrix to represent the grids of individual cropped images

    for (x, y, window) in traversal.sliding_window(image,
                                                   stepSize=60,
                                                   windowSize=(winW, winH)):
        # if the window does not meet our desired window size, ignore it
        if window.shape[0] != winH or window.shape[1] != winW:
            continue

    #	print index
        clone = image.copy()
        cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
        crop_img = image[x:x + winW, y:y + winH]  #crop the image
        list_images[index[0] -
                    1][index[1] -
                       1] = crop_img.copy()  #Add it to the array of images

        average_color_per_row = np.average(crop_img, axis=0)
        average_color = np.average(average_color_per_row, axis=0)
        average_color = np.uint8(average_color)  #Average color of the grids
        #	print (average_color)

        if (any(i <= 240 for i in average_color)):  #Check if grids are colored
            maze[index[1] - 1][index[0] - 1] = 1  #ie not majorly white
            occupied_grids.append(
                tuple(index))  #These grids are termed as occupied_grids
    #		print ("occupied")						#and set the corresponding integer in the maze as 1

        if (any(i <= 20
                for i in average_color)):  #Check if grids are black in color
            #		print ("black obstacles")
            obstacles.append(tuple(index))  #add to obstacles list

        cv2.imshow("Window", clone)
        cv2.waitKey(1)
        time.sleep(0.025)

        #Iterate
        index[1] = index[1] + 1
        if (index[1] > 10):
            index[0] = index[0] + 1
            index[1] = 1
    """
	##########
	#Uncomment this portion to print the occupied_grids (First Part Solution)

	print "Occupied Grids : "
	print occupied_grids
	"""
    """
	#Printing other info
	print "Total no of Occupied Grids : "
	print len(occupied_grids)
	print "Obstacles : "
	print obstacles

	print "Map list: "
	print maze

	print "Map : "
	for x in xrange(10):
		for y in xrange(10):
			if(maze[x][y] == -1):
				print str(maze[x][y]),			
			else:
				print " " + str(maze[x][y]),
		print ""
	"""

    #First part done
    ##############################################################################

    list_colored_grids = [n for n in occupied_grids if n not in obstacles
                          ]  #Grids with objects (not black obstacles)
    """
	print "Colored Occupied Grids : "
	print list_colored_grids
	print "Total no of Colored Occupied Grids : " + str(len(list_colored_grids))
	"""

    #Compare each image in the list of objects with every other image in the same list
    #Most similar images return a ssim score of > 0.9
    #Find the min path from the startimage to this similar image u=by calling astar function

    for startimage in list_colored_grids:
        key_startimage = startimage
        img1 = list_images[startimage[0] - 1][startimage[1] - 1]
        for grid in [n for n in list_colored_grids if n != startimage]:
            img = list_images[grid[0] - 1][grid[1] - 1]
            #		print "for {0} , other images are {1}".format(key_startimage, grid)
            image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            s = ssim(image, image2)
            if s > 0.9:
                result = astarsearch.astar(
                    maze, (startimage[0] - 1, startimage[1] - 1),
                    (grid[0] - 1, grid[1] - 1))
                #			print result
                list2 = []
                for t in result:
                    x, y = t[0], t[1]
                    list2.append(tuple(
                        (x + 1,
                         y + 1)))  #Contains min path + startimage + endimage
                    result = list(list2[1:-1]
                                  )  #Result contains the minimum path required

    #			print "similarity :" +  str(s)
                if not result:  #If no path is found;
                    planned_path[startimage] = list(["NO PATH", [], 0])
                planned_path[startimage] = list(
                    [str(grid), result, len(result) + 1])

    #print "Dictionary Keys pf planned_path:"
    #print planned_path.keys()

    for obj in list_colored_grids:
        if not (planned_path.has_key(obj)):  #If no matched object is found;
            planned_path[obj] = list(["NO MATCH", [], 0])
    """
	##########
	#Uncomment this portion to print the planned_path (Second Part Solution)

	print "Planned path :"
	print planned_path
	"""

    #Second part done
    ##############################################################################

    return occupied_grids, planned_path
def main(image_filename):
    '''
	Returns:
	1 - List of tuples which is the coordinates for occupied grid. 
	2 - Dictionary with information of path. 
	'''

    occupied_grids = []  # List to store coordinates of occupied grid
    planned_path = {
    }  # Dictionary to store information regarding path planning

    # load the image and define the window width and height
    image = cv2.imread(image_filename)
    (winW, winH) = (60, 60)  # Size of individual cropped images

    obstacles = []  # List to store obstacles (black tiles)
    index = [1, 1]  #starting point
    #create blank image, initialized as a matrix of 0s the width and height
    blank_image = np.zeros((60, 60, 3), np.uint8)
    #create an array of 100 blank images
    list_images = [[blank_image for i in xrange(10)]
                   for i in xrange(10)]  #array of list of images
    #empty #matrix to represent the grids of individual cropped images
    maze = [[0 for i in xrange(10)] for i in xrange(10)]

    #traversal for each square
    for (x, y, window) in traversal.sliding_window(image,
                                                   stepSize=60,
                                                   windowSize=(winW, winH)):
        # if the window does not meet our desired window size, ignore it
        if window.shape[0] != winH or window.shape[1] != winW:
            continue

    #	print index, image is our iterator, it's where were at returns image matrix
        clone = image.copy()
        #format square for openCV
        cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
        crop_img = image[x:x + winW, y:y + winH]  #crop the image
        list_images[index[0] -
                    1][index[1] -
                       1] = crop_img.copy()  #Add it to the array of images

        #we want to print occupied grids, need to check if white or not
        average_color_per_row = np.average(crop_img, axis=0)
        average_color = np.average(average_color_per_row, axis=0)
        average_color = np.uint8(average_color)  #Average color of the grids

        #iterate through color matrix,
        if (any(i <= 240 for i in average_color)):  #Check if grids are colored
            maze[index[1] - 1][index[0] - 1] = 1  #ie not majorly white
            occupied_grids.append(
                tuple(index))  #These grids are termed as occupied_grids

        if (any(i <= 20
                for i in average_color)):  #Check if grids are black in color
            #		print ("black obstacles")
            obstacles.append(tuple(index))  #add to obstacles list

        #show this iteration
        cv2.imshow("Window", clone)
        cv2.waitKey(1)
        time.sleep(0.025)

        #Iterate
        index[1] = index[1] + 1
        if (index[1] > 10):
            index[0] = index[0] + 1
            index[1] = 1

    #get object list
    list_colored_grids = [n for n in occupied_grids if n not in obstacles
                          ]  #Grids with objects (not black obstacles)

    #Compare each image in the list of objects with every other image in the same list
    #Most similar images return a ssim score of > 0.9
    #Find the min path from the startimage to this similar image u=by calling astar function

    for startimage in list_colored_grids:
        key_startimage = startimage
        #start image
        img1 = list_images[startimage[0] - 1][startimage[1] - 1]
        for grid in [n for n in list_colored_grids if n != startimage]:
            #next image
            img = list_images[grid[0] - 1][grid[1] - 1]
            #convert to grayscale
            image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            #compare structural similarity
            s = ssim(image, image2)
            #if they are similar
            if s > 0.9:
                #perform a star search between both
                result = astarsearch.astar(
                    maze, (startimage[0] - 1, startimage[1] - 1),
                    (grid[0] - 1, grid[1] - 1))
                #			print result
                list2 = []
                for t in result:
                    x, y = t[0], t[1]
                    list2.append(tuple(
                        (x + 1,
                         y + 1)))  #Contains min path + startimage + endimage
                    result = list(list2[1:-1]
                                  )  #Result contains the minimum path required

                if not result:  #If no path is found;
                    planned_path[startimage] = list(["NO PATH", [], 0])
                planned_path[startimage] = list(
                    [str(grid), result, len(result) + 1])

    for obj in list_colored_grids:
        if not (planned_path.has_key(obj)):  #If no matched object is found;
            planned_path[obj] = list(["NO MATCH", [], 0])

    return occupied_grids, planned_path
Example #5
0
def main(image_filename):

	# 2 arrays
	occupied_grids = []
	planned_path = {}

	#load image
	image = cv2.imread(image_filename)
	(winW, winH) = (60, 60)

	obstacles = []
	index = [1,1]

	#create a blank image with zeros
	blank_image = np.zeros((60,60,3), np.uint8)

	#create an array of 100 blank images
	list_images = [[blank_image for i in range(10)] for i in range(10)]
	maze = [[0 for i in range(10) for i in range(10)]]

	#travesal time!!
	for(x, y, window) in traversal.sliding_window(image, stepSize = 60, windowSize=(winW, winH)):	
		#if the window doesnt meet desired size, ignore 
		if window.shape[0] != winH	 or window.shape[1] != winW:
			continue

		#print index
		clone = image.copy()
		#format the square
		cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0,255,0), 2)
		crop_img = image[x:x + winW, y:y + winH]
		list_images[index[0]-1][index[1]-1] == crop_img.copy()

		#print occupied grid
		average_color_per_row = np.average(crop_img, axis=0)
		average_color = np.average(average_color_per_row, axis  =0)
		average_color = np.uint8(average_color)

		#iterate through the color matrix
		if(any(i <= 240 for i in average_color)):
			maze[index[1]-1][index[0]-1] == 1
			occupied_grids.append(tuple(index))


		if(any(i <=20 for i in average_color)):
			obstacles.append(tuple_index)

		cv2.imshow("window", clone)
		cv2.waitKey(1)
		time.sleep(0.025)



	#get object list
	list_colored_grids = [n for n in occupied_grids if n not in obstacles]	#Grids with objects (not black obstacles)


	#Compare each image in the list of objects with every other image in the same list
	#Most similar images return a ssim score of > 0.9
	#Find the min path from the startimage to this similar image u=by calling astar function

	for startimage in list_colored_grids:
		key_startimage = startimage
		#start image
		img1 = list_images[startimage[0]-1][startimage[1]-1]
		for grid in [n for n in list_colored_grids  if n != startimage]:
			#next image
			img = 	list_images[grid[0]-1][grid[1]-1]
			#convert to grayscale
			image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
			image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
			#compare structural similarity
			s = ssim(image, image2)
			#if they are similar
			if s > 0.9:
				#perform a star search between both
				result = astarsearch.astar(maze,(startimage[0]-1,startimage[1]-1),(grid[0]-1,grid[1]-1))
	#			print result
				list2=[]
				for t in result:
					x,y = t[0],t[1]
					list2.append(tuple((x+1,y+1)))			#Contains min path + startimage + endimage
					result = list(list2[1:-1]) 			#Result contains the minimum path required 

				if not result:						#If no path is found;
					planned_path[startimage] = list(["NO PATH",[], 0])
				planned_path[startimage] = list([str(grid),result,len(result)+1])

	for obj in list_colored_grids:
		if not(obj in planned_path):					#If no matched object is found;
			planned_path[obj] = list(["NO MATCH",[],0])			

	return occupied_grids, planned_path
Example #6
0
def main(image_filename):
    """Do some image processing, iterate through images, determine best path through obstacles"""
    # 2 arrays
    occupied_grids = []  # List to store coordinates of occupied grid
    planned_path = {
    }  # Dictionary to store information regarding path planning

    # load image
    image = cv2.imread(image_filename)
    (win_w, win_h) = (60, 60)

    obstacles = []
    index = [1, 1]

    # create blank image, a matrix of 0's
    blank_image = np.zeros((60, 60, 3), np.uint8)
    # create array of 100 blank images
    list_images = [[blank_image for i in range(10)] for i in range(10)]
    maze = [[0 for i in range(10)] for i in range(10)]

    # image traversal; detect non empty squares
    for (x, y, window) in traversal.sliding_window(image,
                                                   step_size=60,
                                                   window_size=(win_w, win_h)):
        # ignore window if it doesn't meet our size requirements
        if (window.shape[0]) != win_h or window.shape[1] != win_w:
            continue
        # print index, img is our iterator
        clone = image.copy()
        # format the square for open cv
        cv2.rectangle(clone, (x, y), (x + win_w, y + win_h), (0, 255, 0), 2)
        crop_img = image[x:x + win_w, y:y + win_h]
        list_images[index[0] - 1][index[1] - 1] = crop_img.copy()
        # print occupied grid
        average_color_per_row = np.average(crop_img, axis=0)
        average_color = np.average(average_color_per_row, axis=0)
        average_color = np.uint8(average_color)

        # iterate through color matrix
        if any(i <= 240 for i in average_color):
            maze[index[1] - 1][index[0] - 1] = 1  # if not majority white
            occupied_grids.append(tuple(index))

        # add black squares
        if any(i <= 20 for i in average_color):
            obstacles.append(tuple(index))

        cv2.imshow("window", clone)
        cv2.waitKey(1)
        time.sleep(0.05)

        # Iterate
        index[1] = index[1] + 1
        if index[1] > 10:
            index[0] = index[0] + 1
            index[1] = 1

    # perform shortest path search
    list_colored_grids = [n for n in occupied_grids if n not in obstacles]

    for startimage in list_colored_grids:
        # start image
        img1 = list_images[startimage[0] - 1][startimage[1] - 1]
        for grid in [n for n in list_colored_grids if n != startimage]:
            # next image
            img = list_images[grid[0] - 1][grid[1] - 1]
            # convert to grayscale
            image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            # compare structural similarities
            s = ssim(image, image2)

            # if similar, perform a star search
            if s > 0.9:
                result = astarsearch.astar(
                    maze, (startimage[0] - 1, startimage[1] - 1),
                    (grid[0] - 1, grid[1] - 1))
                # print result
                list2 = []
                for t in result:
                    x, y = t[0], t[1]
                    # Contains min path + startimage + endimage
                    list2.append(tuple((x + 1, y + 1)))
                    # Result contains the minimum path required
                    result = list(list2[1:-1])
                if not result:  # If no path is found;
                    planned_path[startimage] = list(["NO PATH", [], 0])
                planned_path[startimage] = list(
                    [str(grid), result, len(result) + 1])

    for obj in list_colored_grids:
        if not obj in planned_path:  # If no matched object is found;
            planned_path[obj] = list(["NO MATCH", [], 0])

    image = cv2.imread(image_filename)
    clone = image.copy()

    drawn = list()

    for obj in planned_path:
        color = list(np.random.choice(range(256), size=3))
        if (planned_path[obj][0] == 'NO MATCH'):
            cv2.putText(clone, "NO MATCH",
                        ((((obj[0] - 1) * 60)), (((obj[1] - 1) * 60) + 30)),
                        cv2.FONT_HERSHEY_SIMPLEX, .35, 0)
            cv2.imshow("window", clone)
            cv2.waitKey()
            continue
        end_str = planned_path[obj][0].strip('(').strip(')').strip()
        end = tuple((int(end_str.split(',')[0]), int(end_str.split(',')[1])))

        # do this so we don't draw duplicate paths the opposite direction
        if (drawn.__contains__(end)):
            continue

        traversal.path_line(clone,
                            start=obj,
                            end=end,
                            path=planned_path[obj][1],
                            color=(int(color[0]), int(color[1]),
                                   int(color[2])))
        drawn.append(obj)
        cv2.imshow("window", clone)
        cv2.waitKey()

    cv2.imshow("window", clone)
    cv2.waitKey()

    return occupied_grids, planned_path
Example #7
0
def main(image_filename):
    filename = os.path.join(dirname, image_filename)

    occupied_grids = []
    planned_path = {}

    #load the image
    image = cv2.imread(filename)
    (winW, winH) = (60, 60)

    obstacles = []
    index = [1, 1]

    #create a blank, initialized a matrix of 0s
    blank_image = np.zeros((60, 60, 3), np.uint8)

    #create an array of 100 blank images
    list_images = [[blank_image for i in range(10)]]
    maze = [[0 for i in range(10) for i in range(10)]]

    #traversal time! detect non-empty squares
    for (x, y, window) in traversal.sliding_window(image,
                                                   stepSize=60,
                                                   windowSize=(winW, winH)):
        # if the window does't meet our desired window size, ignore it
        if window.shape[0] != winH or window.shape[1] != winW:
            continue
        #print index, image is our iterator
        clone = image.copy()
        #format the suqare openCV
        cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
        crop_img = image[x:x + winW, y:y + winH]
        list_images[index[0] - 1][index[1] - 1] = crop_img.copy()

        #print the occupied grids
        average_color_per_row = np.average(crop_img, axis=0)
        average_color = np.average(average_color_per_row, axis=0)
        average_color = np.uint8(average_color)

        #iterate through the color matrix
        if (any(i <= 240 for i in average_color)):
            print(index)
            maze[index[1] - 1][index[0] - 1] = 1
            occupied_grids.append(tuple(index))

        if (any(i <= 20 for i in average_color)):
            obstacles.append(tuple(index))

        cv2.imshow("Window", clone)
        cv2.waitKey(1)
        time.sleep(0.025)

        #Iterate
        index[1] = index[1] + 1
        if (index[1] > 10):
            index[0] = index[0] + 1
            index[1] = 1

    #Now it's time to perform the shortest path search
    #get the list of objects
    list_colored_grids = [n for n in occupied_grids if n not in obstacles]

    for startimage in list_colored_grids:
        key_startimage = startimage
        img1 = list_images[startimage[0] - 1][startimage[1] - 1]
        for grid in [n for n in list_colored_grids if n != startimage]:
            #next image
            img = list_images[grid[0] - 1][grid[1] - 1]
            #convert to grayscale
            image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

            # compare structural similarity
            s = ssim(image, image2)
            #if they are similar, we'll perform a star search
            if s > 0.9:
                #perform a star - search a path - shortest path
                result = astarsearch.astar(
                    maze, (startimage[0] - 1, startimage[1] - 1),
                    (grid[0] - 1, grid[1] - 1))
                #print the result
                list2 = []
                for t in result:
                    x, y = t[0], t[1]
                    list2.append(tuple(x + 1, y + 1))
                    result = list(list2[1:-1])

    for obj in list_colored_grids:
        if not (planned_path.has_key(obj)):
            planned_path[obj] = list(["NO MATCH", [], 0])

    return occupied_grids, planned_path
def main(image_filename):

    occupied_grids = []
    planned_path = {}

    image = cv2.imread(image_filename)
    (winW, winH) = (30, 30)

    obstacles = []
    index = [1, 1]

    blank_image = np.zeros((30, 30, 3), np.uint8)

    list_images = [[blank_image for i in range(60)] for i in range(60)]

    maze = [[0 for i in range(60)] for i in range(60)]

    for (x, y, window) in traversal.sliding_window(image,
                                                   stepSize=30,
                                                   windowSize=(winW, winH)):
        if window.shape[0] != winH or window.shape[1] != winW:
            continue

        clone = image.copy()

        cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
        crop_img = image[x:x + winW, y:y + winH]
        list_images[index[0] - 1][index[1] - 1] = crop_img.copy()

        average_color_per_row = np.average(crop_img, axis=0)
        average_color = np.average(average_color_per_row, axis=0)
        average_color = np.uint8(average_color)

        if (any(i <= 240 for i in average_color)):
            maze[index[1] - 1][index[0] - 1] = 1
            occupied_grids.append(tuple(index))

        if (any(i <= 20 for i in average_color)):
            obstacles.append(tuple(index))

        cv2.imshow("Window", clone)
        cv2.waitKey(1)
        time.sleep(0.030)

        index[1] = index[1] + 1
        if (index[1] > 20):
            index[0] = index[0] + 1
            index[1] = 1

    list_colored_grids = [n for n in occupied_grids if n not in obstacles]

    for startimage in list_colored_grids:
        img1 = list_images[startimage[0] - 1][startimage[1] - 1]
        for grid in [n for n in list_colored_grids if n != startimage]:
            img = list_images[grid[0] - 1][grid[1] - 1]
            image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            image2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            s = ssim(image, image2)
            if s > 0.1:
                result = astarsearch.astar(
                    maze, (startimage[0] - 1, startimage[1] - 1),
                    (grid[0] - 1, grid[1] - 1))
                list2 = []
                for t in result:
                    x, y = t[0], t[1]
                    list2.append(tuple((x + 1, y + 1)))
                    result = list(list2[1:-1])

                if not result:
                    planned_path[startimage] = list(["NO PATH", [], 0])
                planned_path[startimage] = list(
                    [str(grid), result, len(result) + 1])

    return planned_path
Example #9
0
print('starting work, please wait')
start = time.time()
nodes, adjs, adjlf, weights, nodei, hospitals, nearnode, highways, lat, lon, delat, delon, nodesfortest = task2.task2(
    True)
print('testing:')
test = random.sample(nodesfortest, 100)
print('testing astar with dif f:')

for wm in range(1, 4):
    astartime = 0
    for nodep in test:
        astarstart = time.time()
        for i in nearnode:
            dastar, astarpath = a.astar(weights, adjs, nodei.get(nodep),
                                        nodei.get(i), nodes, lat, lon, delat,
                                        delon, adjlf, wm)
        astarend = time.time()
        astartime += astarend - astarstart
    print('astar', wm.__str__() + ':', astartime / 100, 'sec')

print('main testing')
dtime = 0
astartime = 0
levittime = 0
for nodep in test:
    nodeip = nodei.get(nodep)
    dstart = time.time()
    dd, p = dijkstra.adjDijkstra(len(adjlf), nodeip, adjs, weights)
    dend = time.time()
    dtime += dend - dstart
Example #10
0
def main(source, dest, cap, grid_size, frame_width, frame_height, decision):

    occupied_grids = []  # List to store coordinates of occupied grid
    planned_path = {
    }  # Dictionary to store information regarding path planning

    _, image = cap.read()

    image = cv2.resize(image, (frame_width, frame_height))
    # load the image and define the window width and height
    (winW, winH) = (grid_size, grid_size)  # Size of individual cropped images

    obstacles = []  # List to store obstacles (black tiles)
    index = [1, 1]
    blank_image = np.zeros((grid_size, grid_size, 3), np.uint8)
    list_images = [[blank_image for i in range(frame_height // grid_size)]
                   for i in range(frame_width // grid_size)
                   ]  #array of list of images
    maze = [[0 for i in range(frame_height // grid_size)]
            for i in range(frame_width // grid_size)
            ]  #matrix to represent the grids of individual cropped images

    kernel_open = np.ones((2, 2))
    kernel_close = np.ones((5, 5))

    yellow_lower = np.array([20, 45, 27])
    yellow_upper = np.array([30, 255, 255])

    for (x, y, window) in sliding_window(image,
                                         stepSize=grid_size,
                                         windowSize=(winW, winH)):
        # if the window does not meet our desired window size, ignore it
        if window.shape[0] != winH or window.shape[1] != winW:
            continue

        clone = image.copy()
        cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
        crop_img = image[x:x + winW, y:y + winH]  #crop the image
        list_images[index[0] - 1][index[1] - 1] = crop_img.copy()

        img = window

        ctl = img

        hsv = cv2.cvtColor(ctl, cv2.COLOR_BGR2HSV)

        mask0 = cv2.inRange(hsv, yellow_lower, yellow_upper)

        mask = mask0

        mask_op = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel_open)

        mask_cl = cv2.morphologyEx(mask_op, cv2.MORPH_CLOSE, kernel_close)

        Z = mask_cl.reshape((-1, 1))

        Z = np.float32(Z)

        n_colors = 2

        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1)

        flags = cv2.KMEANS_RANDOM_CENTERS

        _, labels, palette = cv2.kmeans(Z, n_colors, None, criteria, 10, flags)

        _, counts = np.unique(labels, return_counts=True)

        dominant = palette[np.argmax(counts)]

        center = np.uint8(palette)

        res = center[labels.flatten()]

        res2 = res.reshape((mask_cl.shape))

        # cv2.imshow('res2',res2)

        print('decision' + str(decision))
        if decision == 1:
            flag = 0
            # print(palette)
            for i in palette:
                if i[0] >= 250:
                    # print(i)
                    if (flag == 0):
                        maze[index[1] - 1][index[0] - 1] = 1
                        cv2.rectangle(image, (x, y), (x + winW, y + winH),
                                      (255, 0, 0), -1)
                        occupied_grids.append(tuple(index))
                        flag = 1

            cv2.putText(clone, str(maze[index[1] - 1][index[0] - 1]), (x, y),
                        cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2,
                        cv2.LINE_AA)

        cv2.imshow("window", clone)
        cv2.waitKey(1)

        #Iterate
        index[1] = index[1] + 1
        if (index[1] > (frame_width // grid_size)):
            index[0] = index[0] + 1
            index[1] = 1

    # Apply astar algorithm on the give maze image
    res = [[maze[j][i] for j in range(len(maze))] for i in range(len(maze[0]))]
    result = astarsearch.astar(res, (source[0], source[1]), (dest[0], dest[1]),
                               frame_width // grid_size,
                               frame_height // grid_size)

    list2 = []

    for t in result:
        x, y = t[0], t[1]
        list2.append(tuple(
            (x + 1, y + 1)))  #Contains min path + startimage + endimage
    result = list(list2[1:-1])  #Result contains the minimum path required

    key = cv2.waitKey(1)

    if key == 27:
        cv2.destroyAllWindows()
        cap.release()

    return occupied_grids, list2
Example #11
0
def main(source , dest, cap, grid_size,frame_width, frame_height,decision):

	occupied_grids = []		# List to store coordinates of occupied grid 
	planned_path = {}		# Dictionary to store information regarding path planning  	
	# print('aewfoineoif')
	# cap = cv2.VideoCapture(0)

	# image = cv2.imread(im)

	_,image = cap.read()

	image = cv2.resize(image , (frame_width, frame_height))
	# load the image and define the window width and height
	# image = cv2.imread(frame)
	(winW, winH) = (grid_size, grid_size)		# Size of individual cropped images 

	obstacles = []			# List to store obstacles (black tiles)  
	index = [1,1]
	blank_image = np.zeros((grid_size,grid_size,3), np.uint8)
	list_images = [[blank_image for i in range(frame_height//grid_size)] for i in range(frame_width//grid_size)] 	#array of list of images 
	maze = [[0 for i in range(frame_height//grid_size)] for i in range(frame_width//grid_size)] 			#matrix to represent the grids of individual cropped images


	kernel_open  = np.ones((2,2))
	kernel_close = np.ones((5,5))
	
	yellow_lower = np.array([20, 100, 100])
	yellow_upper = np.array([30, 255, 255])

	for (x, y, window) in traversal.sliding_window(image, stepSize=grid_size, windowSize=(winW, winH)):
		# if the window does not meet our desired window size, ignore it
		if window.shape[0] != winH or window.shape[1] != winW:
			continue

	#	print index
		clone = image.copy()
		crop_img = clone[x:x + winW, y:y + winH] 				#crop the image
		list_images[index[0]-1][index[1]-1] = crop_img.copy()		
		cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
		

		img = crop_img

		cv2.imshow("second_window",img)
		ctl = img
	

		# hsv = cv2.cvtColor(ctl, cv2.COLOR_BGR2HSV)

		# hue,sat,val,ret = cv2.mean(hsv)
		# print(cv2.mean(hsv))

		# t_val = 160
		# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
		# lower = np.array([0, 0, 0]) #black color mask
		# upper = np.array([t_val, t_val, t_val])
		# mask = cv2.inRange(img, lower, upper)

		# ret,thresh = cv2.threshold(mask,127,255,cv2.THRESH_BINARY)
		# contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
		# cv2.drawContours(image,contours,-1,(0,255,0),3)

		# biggest = 0
		# max_area = 0
		# min_size = thresh.size/4
		# index1 = 0
		# peri = 0
		# for i in contours:
		# 	area = cv2.contourArea(i)
		# 	if area > 10000:
		# 		peri = cv2.arcLength(i,True)

		# 	if area > max_area:
		# 		biggest = index1
		# 		max_area = area
		# 		index1 = index1 + 1
		

		# approx = cv2.approxPolyDP(contours[biggest],0.05,True)

		# cv2.polylines(image, [approx], True, (0,255,0), 3)

		# mask0 = cv2.inRange(hsv, yellow_lower, yellow_upper)

		# mask = mask0

		# mask_op = cv2.morphologyEx(mask , cv2.MORPH_OPEN, kernel_open)

		# mask_cl = cv2.morphologyEx(mask_op, cv2.MORPH_CLOSE, kernel_close)

		# Z = mask_cl.reshape((-1,1))

		# Z = np.float32(Z)

		# n_colors = 2

		# criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1)

		# flags = cv2.KMEANS_RANDOM_CENTERS

		# _, labels, palette = cv2.kmeans(Z, n_colors, None, criteria, 10, flags)

		# _, counts = np.unique(labels, return_counts=True)

		# dominant = palette[np.argmax(counts)]

		# center = np.uint8(palette)

		# res = center[labels.flatten()]

		# res2 = res.reshape((mask_cl.shape))

		# cv2.imshow('res2',res2)

		
		if decision==1:
			# flag = 0
			# # print(palette)
			# for i in palette:
			# 	if i[0]>=250:
			# 		# print(i)
			# 		if (flag==0):
			#if(hue==0 and sat==255 and val==255):

			# elif(hue==60 and sat==255 and val==255):

			if (val==0):
				maze[index[1]-1][index[0]-1] = 1		
				cv2.rectangle(image, (x, y),(x + winW, y + winH), (255, 0, 0),-1)		
				occupied_grids.append(tuple(index))	
				flag = 1
			
			cv2.putText(clone,str(maze[index[1]-1][index[0]-1]),(x, y),
				cv2.FONT_HERSHEY_SIMPLEX ,1
				,(255,0,0),2, cv2.LINE_AA)

			# cv2.putText(clone,str(maze[index[1]-1][index[0]-1]),(x, y),
			# 	cv2.FONT_HERSHEY_SIMPLEX ,1
			# 	,(255,0,0),2, cv2.LINE_AA)


		# cv2.imshow("hist", hist)
		# cv2.imshow("bar", bar)
		cv2.imshow("display_Window", clone)
		cv2.waitKey(1)
		time.sleep(0.02)
	
		#Iterate
		index[1] = index[1] + 1							
		if(index[1]>(frame_width//grid_size)):
			index[0] = index[0] + 1
			index[1] = 1
	
	# Apply astar algorithm on the give maze image 
	res = [[maze[j][i] for j in range(len(maze))] for i in range(len(maze[0]))]
	result = astarsearch.astar(res,(source[0],source[1]),(dest[0],dest[1]), frame_width//grid_size, frame_height//grid_size)
	
	# printing the maze for checking
	# for i in range(len(maze)):
	# 	for j in range(len(maze[0])):
	# 		print(res[i][j],end=" ")
	# 	print(" ")	
	
	list2=[]
	# print(result)
	for t in result:
		x,y = t[0],t[1]
		list2.append(tuple((x+1,y+1)))			#Contains min path + startimage + endimage
	result = list(list2[1:-1]) 			#Result contains the minimum path required 

	# print(maze)
	# cv2.destroyAllWindows()
	# cap.release()
	key = cv2.waitKey(1)
	if key==27:
		cv2.destroyAllWindows()
		cap.release()

	return occupied_grids, list2