Reputation: 145
I'm working on a project that involves automatically clicking on objects in a video game as they appear on the screen. Naturally, each object has a distinct blue outline - so I've isolated all colors from the image except for that blue color.
The image below shows an example of a pre-processed screenshot of the game. Using OpenCV in Python, how can I:
E.g.,
Upvotes: 0
Views: 239
Reputation: 27547
You can use a relatively less-known cv2
method cv2.moments()
:
import cv2
img = cv2.imread("image.png")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 128, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
moments = cv2.moments(cnt)
center_x = int(moments["m10"] / moments["m00"])
center_y = int(moments["m01"] / moments["m00"])
top_x, top_y = cnt[cnt[..., 1].argmin()][0]
cv2.circle(img, (center_x, center_y), 3, (0, 0, 255), -1)
cv2.circle(img, (top_x, top_y), 3, (0, 0, 255), -1)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Input image:
Output image:
The variable names explain the code pretty well already, after all, Python is similar to plain English!
Upvotes: 5