如何在Python中将二进制图像的内容/对象居中?

2023-11-30

我有一个计算图形方向的代码。然后根据这个方向旋转图形,直到它变直。这一切都很好。我正在努力解决的问题是将旋转图形的中心移至整个图像的中心。所以图形的中心点应该与整个图像的中心点相匹配。

Input image: enter image description here

code:

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)

带输出:

enter image description here

正如您所看到的,白色图形稍微偏左,我希望它完全居中。 有谁知道如何做到这一点?

EDIT:我尝试了@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)

这是 Python/OpenCV 中的一种方法。

从轮廓中获取白色区域的边界框。计算居中区域的偏移量。使用 numpy 切片将其复制到输入大小的黑色背景的中心。

Input:

enter image description here

import cv2
import numpy as np

# read image as grayscale
img = cv2.imread('white_shape.png', cv2.COLOR_BGR2GRAY)

# get shape
hh, ww = img.shape


# get contours (presumably just one around the nonzero pixels) 
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)

# recenter
startx = (ww - w)//2
starty = (hh - h)//2
result = np.zeros_like(img)
result[starty:starty+h,startx:startx+w] = img[y:y+h,x:x+w]

# view result
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save reentered image
cv2.imwrite('white_shape_centered.png',result)


enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中将二进制图像的内容/对象居中? 的相关文章