问题描述
我的目标是创建一个在每个边界内包含旋转角度作为文本的图像。图像应包括彩色边界(我已确定)和每个边界内的角度值(我没有确定)。
PYTHON代码
import matplotlib.pyplot as plt
import cv2
import numpy as np
import csv
mask = cv2.imread('patch_mask.png')
mask = cv2.resize(mask,(400,400))
mask_gray = cv2.cvtColor(mask,cv2.COLOR_BGR2GRAY)
ret2,th2 = cv2.threshold(mask_gray,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Otsu's
method
image = cv2.imread('patch_image.png')
image_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image_enhanced = cv2.equalizeHist(image_gray)
# process image
boundary_output = "/Desktop/mat2py/mask_boundary.png"
ellipse_output = "/Desktop/mat2py/ellipse.png"
colormap_output = "/Desktop/mat2py/colormap.png"
# im = cv2.imread("patch_mask.png")
imgray = cv2.cvtColor(mask,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,0)
# find contours in the binary image
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
tmp = np.zeros_like(mask)
tmp2 = np.zeros_like(mask)
boundary = cv2.drawContours(tmp,contours,-1,(255,255),1)
# calculate moments and extract cell shape info
moment_dict = {}
for index,cnt in enumerate(contours):
moment_dict[index] = cv2.moments(cnt)
# creating a csv file named coordinates
with open('/Desktop/mat2py/coordinates.csv','w',newline='') as newFile:
newFileWriter = csv.writer(newFile)
newFileWriter.writerow(
["Center_x","Center_y","(Center_x,Center_y)","(Major Axis,Minor Axis)","Rotation Angle"])
obj_properties = {}
for index,obj_moments in moment_dict.items():
cx,cy = obj_moments['m10'] / obj_moments['m00'],obj_moments['m01'] / obj_moments['m00']
ellipse = (x,y),(MA,ma),angle = cv2.fitEllipse(contours[index])
props = {'Center_x': cx,'Center_y': cy,'Major Axis': MA,'Minor Axis': ma,'Rotated Angle': angle}
ellipse_image = cv2.ellipse(imgray,ellipse,255))
obj_properties[index] = props
newFileWriter.writerow([cx,cy,(x,angle])
all_the_angle = [v['Rotated Angle'] for k,v in obj_properties.items()]
min_angle = 0
max_angle = 180
range_angle = max_angle - min_angle
# color mapping of Rotated Angle scalars to BGR values
cmap = plt.cm.get_cmap('jet')
for index,prop in obj_properties.items():
v = (prop['Rotated Angle'] - min_angle) / range_angle
r,g,b,a = [int(x) for x in cmap(v,bytes=True)]
color_input = (b,r)
colormap_image = cv2.drawContours(image,index,color_input,2)
plt.imshow(colormap_image,cmap=cmap)
cbar = plt.colorbar()
cbar.ax.set_yticklabels([]) # vertically oriented colorbar
cbar.set_label('Angle (Degree)')
plt.show()
# save the boundary,and colormap image
plt.imsave(boundary_output,boundary,cmap="gray")
cv2.imwrite(ellipse_output,ellipse_image)
colormap_image = plt.savefig(colormap_output)
# cv2.imwrite(colormap_output,colormap_image)
print("Saved contours,boundaries,ellipse and colormap as images and csv")
这些是我使用的图像。 patch_image patch_mask
我明白了。 patch_colormap
如何显示每个轮廓的旋转角度?例如,在每个边界内,我要添加其旋转角度的文本。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)