I can not perform color conversion after rotating image

0

I'm developing an algorithm that rotates images by 10 degrees. For this, I am identifying the center of my region of interest, not the center of the image, because it has region of interest that are close to the songs. With this I can rotate each centered image, maintaining the original dimensions of the image. The problem I'm having is that by identifying the center of the image, I convert the input image to grayscale, so I can not convert the rotated image to the 'original' color.

Follow the code below:

import cv2
import numpy as np

POS_ROT_STEP = 18
IMG = 'IMG006'

img = cv2.imread(IMG+'.png')

gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
_, contours,hierarchy = cv2.findContours(gray,2,1)
cnt = contours

for i in range (len(cnt)):
    (x,y),radius = cv2.minEnclosingCircle(cnt[i])
    center = (int(x),int(y))
    print ('Circle: ' + str(i) + ' - Center: ' + str(center) + ' - Radius: ' + str(radius))

# girando e cortando a imagem para produzir amostras sinteticas
for j in range(1, POS_ROT_STEP):
    (h, w) = img.shape[:2]

    rotated = cv2.getRotationMatrix2D(centro, -(360 / POS_ROT_STEP) * j, 1.0)

    nx = img.shape[1]
    ny = img.shape[0]

    rotated[0, 2] += (nx / 2) - x
    rotated[1, 2] += (ny / 2) - y

    output_aux = cv2.warpAffine(gray, rotated, (nx, ny))
    backtorgb = cv2.cvtColor(output_aux,cv2.COLOR_GRAY2RGB)
    cv2.imwrite('~/rotate/'+IMG+'-'+str( j )+'.png', backtorgb)
    
asked by anonymous 07.12.2018 / 15:42

1 answer

2

After converting to gray, you lose all BGR color information. Then it is not possible to convert from gray to color.

What happens when you convert from gray scale to BGR with cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) is the creation of 3 channels, but all with equal values. For it was in grayscale.

Example

A pixel that has the following grayscale value: (127) , after conversion will have three channels: (127, 127, 127)

Alternative

An alternative to this problem is to save a copy of the original image with: copia = img.copy()

And after finding the coordinates in gray scale , work on the original image.

Note

The standard OpenCV color space is BGR , so when loading the image with img = cv2.imread(IMG+'.png') , it is in the BGR color space.

So the gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) conversion should be gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    
07.12.2018 / 16:43