简体   繁体   中英

Rotate image based in centroid using the rotation matrix

I found this article were this guys rotated one egg image using the centroid. I found the centroid based in the OTSU image:

_, thr = cv2.threshold(grayscale, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
moment = cv2.moments(thr)
if moment['m00'] !=0 :
    centroid = (int(moment['m10'] / moment['m00']), int(moment['m01'] / moment['m00']))
    cv2.circle(result, centroid, 3, (0, 255, 0), -1)
    showImage(result, "Centroid")

在此处输入图像描述

The reasearches recomends use the rotation matrix to rotate the image using the centroid:

在此处输入图像描述

Could you help me how use the rotation matrix using opencv?

This is my current method, recently I found the centroid:

Input images:

在此处输入图像描述

在此处输入图像描述

def showImage(img, titulo):
    plt.figure(figsize=(5,5))
    plt.title(titulo)
    plt.imshow(img)
    plt.show()

# Segmentar
imagePath = "images/sample1.jpeg"
image = cv2.imread(imagePath)
# convertir de formato BGR a RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
original = image
# Mostrar imagen original
showImage(image, "Imagen Original")

#Aplicar filtro paso bajo (blur)
image = cv2.blur(image,(9,9),0)
    
# Convertir a HSV:
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Mostrar canal R el cual el huevo presenta mayor contraste
showImage(hsv, "hsv image")

# Convertir escala de grises el hsv
grayscale = cv2.cvtColor(hsv, cv2.COLOR_RGB2GRAY)
showImage(grayscale, "Escala de grises hsv")

# Aplicar binarización OTSU
_, thr = cv2.threshold(grayscale, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

showImage(thr, "OTSU imagen")

# Poner máscara thr a la imágen original

result = cv2.bitwise_and(original, original, mask=thr)

showImage(result, "Imagen segmentada")

# Buscar centroide
moment = cv2.moments(thr)
if moment['m00'] !=0 :
    centroid = (int(moment['m10'] / moment['m00']), int(moment['m01'] / moment['m00']))
    cv2.circle(result, centroid, 3, (0, 255, 0), -1)
    showImage(result, "Centroid")

You can use the warp functions including warpAffine and warpPerspective in OpenCV. It seems that the warpAffine (affine transform) would be enough for your application. Anyway, you could simply use the below piece of code:

Point center = Point( image.cols/2, image.rows/2 );
Mat rot_mat = getRotationMatrix2D( center, angle, scale ); // rot_mat is 2x3 double matrix), you can set scale=1
Mat warp_rotate_dst;
warpAffine( image, warp_rotate_dst, rot_mat, image.size());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM