1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| from ultralytics import YOLO import cv2 import numpy as np import os import requests import subprocess
def check_status(): try: requests.get("http://127.0.0.1:53516/preview") return True except requests.RequestException: return False
def get_clipped_img(): img = requests.get("http://127.0.0.1:53516/preview") img = cv2.imdecode(np.array(bytearray(img.content)),-1) height,width = img.shape[:2] clip = (height - width) / 2 img = img[int(clip-50):int(height-clip+50),0:int(width)] img = cv2.resize(img, (1080, 1080)) cv2.imwrite("./tmp.png", img) img = cv2.imread("./tmp.png") return img
def get_loc_by_point(x,y): x = int(x / 120) y = int(y / 108) return x,y
def printBoard(board,names): text = np.char.asarray(board) for x in range(10): for y in range(9): if board[x,y] != -1: text[x,y] = names[board[x,y]] else: text[x,y] = "empty" print(board) print(text) device = "127.0.0.1:16416" os.system("adb connect %s" % device)
if check_status(): print("DroidCast_raw is running") else: print("try start DroidCast_raw") os.system("adb -s %s push DroidCast_raw.apk /data/local/tmp" % device) os.system("adb -s %s forward tcp:53516 tcp:53516" % device) subprocess.Popen(["adb","-s",device,"shell","CLASSPATH=/data/local/tmp/DroidCast_raw.apk nohup app_process / ink.mol.droidcast_raw.Main --port=53516 &"],shell=True)
model = YOLO("jjchess.pt") type = -1 board = np.zeros([10,9],dtype=int) board.fill(-1) while True: img = get_clipped_img() results = model(img, stream=True) for result in results: boxes = result.boxes names = result.names for box in boxes: id = box.cls.cpu().numpy()[0] name = f"{names[id]}" if not name.startswith("black") and not name.startswith("red"): continue x1, y1, x2, y2 = map(int, box.xyxy.cpu().numpy()[0]) cx,cy = int((x1 + x2) / 2),int((y1 + y2) / 2) x,y = get_loc_by_point(cx,cy) board[y,x] = id if x == 4 and y == 9: if name == "red_boss": type = 0 if name == "black_boss": type = 1 cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.circle(img, (cx, cy), 10, (0, 0, 255), -1) cv2.putText(img, f"{name}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.putText(img, f"({x},{y})", (x1, y2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2) printBoard(board,names) if type != -1 and type == 0: print("AI red") else: print("AI black") board.fill(-1)
img = cv2.resize(img, (640, 640)) cv2.imshow("Frame", img) if cv2.waitKey(1) & 0xFF == ord('q'): break
|