그림의 방향을 계산하는 코드가 있습니다. 이 방향에 따라 그림이 곧게 펴질 때까지 회전합니다. 이 모든 것이 잘 작동합니다. 내가 고생하는 것은 회전 된 그림의 중심을 전체 이미지의 중심으로 가져 오는 것입니다. 따라서 그림의 중심점이 전체 이미지의 중심점과 일치해야합니다.
암호:
import cv2
import numpy as np
import matplotlib.pyplot as plt
path = "inputImage.png"
image=cv2.imread(path)
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh=cv2.threshold(gray,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
contours,hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
cnt1 = contours[0]
cnt=cv2.convexHull(contours[0])
angle = cv2.minAreaRect(cnt)[-1]
print("Actual angle is:"+str(angle))
rect = cv2.minAreaRect(cnt)
p=np.array(rect[1])
if p[0] < p[1]:
print("Angle along the longer side:"+str(rect[-1] + 180))
act_angle=rect[-1]+180
else:
print("Angle along the longer side:"+str(rect[-1] + 90))
act_angle=rect[-1]+90
#act_angle gives the angle of the minAreaRect with the vertical
if act_angle < 90:
angle = (90 + angle)
print("angleless than -45")
# otherwise, just take the inverse of the angle to make
# it positive
else:
angle=act_angle-180
print("grter than 90")
# rotate the image to deskew it
(h, w) = image.shape[:2]
print(h,w)
center = (w // 2, h // 2)
print(center)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h),flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
plt.imshow(rotated)
cv2.imwrite("rotated.png", rotated)
출력 포함 :
보시다시피 흰색 그림이 약간 왼쪽에 배치되어 있으므로 완벽하게 중앙에 배치하고 싶습니다. 누구든지 이것이 어떻게 할 수 있는지 알고 있습니까?
편집 : 나는 @joe의 제안을 시도하고 그림의 너비와 높이를 2로 나누어 이미지의 중심에서 중심 좌표를 뺍니다. 이것에서 오프셋이 생겼습니다.이를 설명하는 배열에 추가해야했습니다. 영상. 하지만 배열에 오프셋을 추가하는 방법을 모르겠습니다. x 및 y 좌표에서 어떻게 작동합니까?
코드:
img = cv2.imread("inputImage")
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray_image,127,255,0)
height, width = gray_image.shape
print(img.shape)
wi=(width/2)
he=(height/2)
print(wi,he)
M = cv2.moments(thresh)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
offsetX = (wi-cX)
offsetY = (he-cY)
print(offsetX,offsetY)
print(cX,cY)
한 가지 접근 방식은 바이너리 개체의 경계 상자 좌표를 얻은 다음 Numpy 슬라이싱을 사용하여 ROI를 자르는 것입니다. 여기에서 새로운 이동 된 좌표를 계산 한 다음 ROI를 새 빈 마스크에 붙여 넣습니다.
암호
import cv2
import numpy as np
# Load image as grayscale and obtain bounding box coordinates
image = cv2.imread('1.png', 0)
height, width = image.shape
x,y,w,h = cv2.boundingRect(image)
# Create new blank image and shift ROI to new coordinates
mask = np.zeros(image.shape, dtype=np.uint8)
ROI = image[y:y+h, x:x+w]
x = width//2 - ROI.shape[0]//2
y = height//2 - ROI.shape[1]//2
mask[y:y+h, x:x+w] = ROI
cv2.imshow('ROI', ROI)
cv2.imshow('mask', mask)
cv2.waitKey()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다