0% found this document useful (0 votes)
15 views

Webcam For 3x3 Rubix - Struct Python

The document describes a Python program that can detect the colors of a Rubik's Cube using computer vision and solve it by calling a Rubik's Cube solver library. It uses OpenCV to capture video from a webcam, detect colored contours to identify each cubelet, and pass the colors to the solver library to get the solution steps.

Uploaded by

phong09829
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Webcam For 3x3 Rubix - Struct Python

The document describes a Python program that can detect the colors of a Rubik's Cube using computer vision and solve it by calling a Rubik's Cube solver library. It uses OpenCV to capture video from a webcam, detect colored contours to identify each cubelet, and pass the colors to the solver library to get the solution steps.

Uploaded by

phong09829
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python

Friday, December 22, 2023 7:03 PM

import cv2
import numpy as np
from rubik_solver import Solver

# Các hằng số
COLOR_MAPPING = {
"green": "F",
"blue": "B",
"white": "U",
"yellow": "D",
"orange": "L",
"red": "R"
}
LOWER_BOUND = np.array([0, 100, 100])
UPPER_BOUND = np.array([10, 255, 255])
MIN_CONTOUR_AREA = 100

# Hàm nhận diện màu sắc


def detect_colors(frame):
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, LOWER_BOUND, UPPER_BOUND)

contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

centers = []
for contour in contours:
area = cv2.contourArea(contour)
if area > MIN_CONTOUR_AREA:
moments = cv2.moments(contour)
if moments["m00"] != 0:
cx = int(moments["m10"] / moments["m00"])
cy = int(moments["m01"] / moments["m00"])
centers.append((cx, cy))

return centers

# Hàm giải Rubik's Cube


def solve_rubiks_cube(colors):
cube_state = "".join(COLOR_MAPPING[color] for color in colors)
solution = Solver().solve(cube_state)
print("Rubik's Cube Solution:", solution)

# Khởi tạo webcam


cap = cv2.VideoCapture(0)

while True:
ret, frame = cap.read()
centers = detect_colors(frame)

New Section 1 Page 1


for center in centers:
cv2.circle(frame, center, 5, (0, 255, 0), -1)

cv2.imshow("Rubik's Cube Solver", frame)

# Nếu nhận diện đủ số lượng mảnh màu, thì giải Rubik's Cube
if len(centers) == 6:
solve_rubiks_cube(["green", "blue", "white", "yellow", "orange", "red"])
break

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


break

cap.release()
cv2.destroyAllWindows()

New Section 1 Page 2

You might also like