import cv2
import numpy as np
def cv_show(neme, img):
cv2.imshow(neme, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
print(cv2.RETR_LIST, cv2.RETR_EXTERNAL, cv2.RETR_CCOMP, cv2.RETR_TREE)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
sd = cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
cv_show('sd', sd)
cnt = contours[0]
x, y, w, h = cv2.boundingRect(cnt)
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
cv_show('sad', img)
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], -1, (0, 255, 0), 1)
cv_show("s", img)
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0, 0, 255), 1)
cv_show('sad', img)
epsilon = 0.1 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
cv2.polylines(img, [approx], True, (0, 255, 255), 2)
cv_show('sad', img)
hull = cv2.convexHull(cnt)
i = cv2.polylines(img, [hull], True, (255, 255, 0), 2)
cv_show("s", img)
leftmost = tuple(cnt[cnt[:, :, 0].argmin()][0])
rightmost = tuple(cnt[cnt[:, :, 0].argmax()][0])
topmost = tuple(cnt[cnt[:, :, 1].argmin()][0])
bottommost = tuple(cnt[cnt[:, :, 1].argmax()][0])
cv2.line(img, leftmost, leftmost, (255, 0, 0), 5)
cv2.line(img, rightmost, rightmost, (255, 0, 0), 5)
cv2.line(img, topmost, topmost, (255, 0, 0), 5)
cv2.line(img, bottommost, bottommost, (255, 0, 0), 5)
cv_show("s", img)
(x, y), (MA, ma), angle = cv2.fitEllipse(cnt)
print(x, y, MA, ma, angle)