0

I am making an AI that can play the game connect 4, from a picture of one state of the game e.g : click to see

This script below, is detecting red elements from a picture:

import cv2
import numpy as np
 
img = cv2.imread('connect.png')
 
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
 
#get red color 
lower_range = np.array([169, 100, 100])
upper_range = np.array([189, 255, 255])
 
mask = cv2.inRange(hsv, lower_range, upper_range)
 
cv2.imshow('image', img)
cv2.imshow('mask', mask)
 
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here

I would like to insert these data into a 2D array to be able to use this array as a game state and determine which move the AI should make.

I have tried to find a solution on Stack Overflow and on Internet but overall I didn't find anything about it.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Shane
  • 23
  • 8
  • 1
    have you looked at this example https://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html – jayprich Jul 18 '20 at 18:18
  • @jayprich thank you for your answer this is useful to find all tokens by color because in my case I can save coin.png and use it like in the example ! – Shane Jul 19 '20 at 11:33

1 Answers1

1

This is a way to read a picture and to cast it in a 2-dimensional numpy array with np.array(in_image):

import numpy as np
import skimage
from skimage import io, transform


path = "C:/my/path/"
pic = 'myPic.png'
imgName = path+pic

in_image_0 = skimage.io.imread(imgName)                   # read the image
in_image_1 = skimage.color.rgb2gray(in_image_0)           # transform it to grey-scale
in_image_2 = skimage.transform.rescale(in_image_1, 0.5)   # change the resolution
in_image_3 = np.flipud(np.array(in_image_2))              # make a numpy array and flip it up/down
pyano
  • 1,885
  • 10
  • 28
  • I would just add that you need to open your file like this path =r "C:/my/path/"" – Shane Jul 19 '20 at 11:34
  • But how can I determine what is the color value and the positionning of it in the image with this method – Shane Jul 19 '20 at 12:03
  • There are many different ways to do that. Search for `skimage color detecting` e.g. – pyano Jul 19 '20 at 19:32
  • https://www.google.com/search?source=univ&tbm=isch&q=skimage++color+detecting&client=firefox-b-d&sa=X&ved=2ahUKEwjrjY6HhtrqAhWuVBUIHVy2BrcQsAR6BAgKEAE&biw=1920&bih=938#imgrc=F9GGBdLsxeWH3M – pyano Jul 19 '20 at 19:33
  • https://stackoverflow.com/questions/2270874/image-color-detection-using-python – pyano Jul 19 '20 at 19:37