Skip to content
Snippets Groups Projects
Commit 82e597a7 authored by Aldo Ignacio Arriola Cordova's avatar Aldo Ignacio Arriola Cordova
Browse files

tarea classe05

parent 08354e01
No related branches found
No related tags found
No related merge requests found
.ipynb_checkpoints/
This diff is collapsed.
# ejercicios-clase-05-datos
## Alumno: Aldo Arriola
```python
import numpy as np
import matplotlib.pyplot as plt
```
```python
def imshow(im,figsize=(10,8), cm=None):
'''directly show an image
'''
plt.figure(figsize=figsize)
plt.imshow(im, cmap=cm)
```
```python
!ls data
```
zapatocaImage.jpeg
```python
image = plt.imread("./data/zapatocaImage.jpeg")
type(image)
```
numpy.ndarray
```python
imageR, imageG, imageB = image[:, :, 0], image[:, :, 1], image[:, :, 2]
```
```python
image.shape
```
(789, 1184, 3)
```python
imageR.shape
```
(789, 1184)
### Función para convertir RGB a grises
Empleando el teorema de pitagoras para obtener una magnitud resultante, dado que las imágenes deben tener valores de 8bits, con la función numpy.clip escalamos a valores de 0-255.
<img src=https://www.researchgate.net/profile/Jan-Christoph_Otto/publication/235875086/figure/fig6/AS:393488018493461@1470826262981/A-red-green-and-blue-RGB-color-cube-The-cube-defines-the-intensity-of-each-primary.png width="200">
\begin{equation}
Y=\sqrt{R^2+G^2+B^2}
\end{equation}
Donde $Y$ es el valor de la magnitud de gris no normalizada a 8bits
```python
def mytest_rgb2gray(im_red, im_green, im_blue):
im_gray = np.sqrt(np.power(im_red, 2) + np.power(im_green, 2) + np.power(im_blue, 2))
im_gray = np.clip(im_gray, 0, 255)
im_gray = np.asarray(im_gray,dtype='uint8')
return im_gray
```
### Función basada en la definición de gris
Para convertir de RGB a escala de grises, según este [post](https://en.wikipedia.org/wiki/Grayscale), se usa la siguiente ecuación
\begin{equation}
Y=0.2126 R+0.7152 G+0.0722 B
\end{equation}
```python
def rgb2gray(im_red, im_green, im_blue):
y = 0.2126*im_red + 0.7152*im_green +0.00722*im_blue
y = np.clip(y, 0,255)
return np.asarray(y,dtype='uint8')
```
### Probamos las imágenes resultantes de las dos funciones
```python
my_im_gray = mytest_rgb2gray(imageR, imageG, imageB)
im_gray = rgb2gray(imageR, imageG, imageB)
```
```python
print(my_im_gray.dtype, my_im_gray.shape)
```
uint8 (789, 1184)
```python
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16,8))
ax1.imshow(my_im_gray)
ax2.imshow(im_gray)
```
<matplotlib.image.AxesImage at 0x7f6c0119fb38>
![png](output_15_1.png)
### OK, mytest_rgb2gray no funcionó
Además, la imagen en escala de grises se muestra en una tonalidad azul
```python
plt.figure(figsize=(10,8))
plt.imshow(im_gray, cmap="gray")
plt.show()
```
![png](output_17_0.png)
### Identificamos las estrellas
Las estrellas se pueden distinguir por el contraste con el cielo. Las estrwellas son más blancas en comparación con el cielo que es más oscuro
#### Seleccionando manualmente una estrella
Según las coordenadas que nos da el gráfico, la estrella más grande se encuentra alrededor de los indices (aproximadamente) (550,670). Con estos valores se iniciará el recorte de la imagen de la estrella.
```python
star0 = im_gray[550-30:550+30, 670-30:670+30]
imshow(star0,(5,4))
```
![png](output_20_0.png)
```python
star0 = star0[20:45, 12:35]
imshow(star0,(5,4))
plt.colorbar()
```
<matplotlib.colorbar.Colorbar at 0x7f6be193f7f0>
![png](output_21_1.png)
### 2D Gaussian Fit
Para cada estrella se realizara un ajuste a una función Gaussiana 2D. Se define la función de gauss en el dominio $XY$ como
\begin{equation}
G(x,y)=A_0\exp{(-\frac{x^2+y^2}{2\sigma^2})}
\end{equation}
Dado que se cuenta con el cielo "vacio" y este no es completamente oscuro o negro, se agrega una constante $c_0$, además, debido a que no son centradas en el origen las estrellas agregamos los factores de desplazamiento $x_0$ y $y_0$
\begin{equation}
G(x,y)=A_0\exp{(-\frac{(x-x_0)^2+(y-y_0)^2}{2\sigma^2})}+c_0
\end{equation}
Para llevar a cabo el ajuste usamos la función curve_fit() de la librería scipy.
```python
def gaussian2d(xy, x0, y0, a0, sigma, c0):
g = a0*np.exp(-((xy[0]-x0)**2 + (xy[1]-y0)**2)/(2*sigma**2)) + c0
return g.ravel()
```
```python
# instalación de scipy
#!pip3 install --user scipy
```
Collecting scipy
[?25l Downloading https://files.pythonhosted.org/packages/b6/3a/9e0649ab2d5ade703baa70ef980aa08739226e5d6a642f084bb201a92fc2/scipy-1.6.1-cp37-cp37m-manylinux1_x86_64.whl (27.4MB)
 100% |████████████████████████████████| 27.4MB 44kB/s eta 0:00:011
[?25hRequirement already satisfied: numpy>=1.16.5 in /home/arriolaa/.local/lib/python3.7/site-packages (from scipy) (1.19.5)
Installing collected packages: scipy
Successfully installed scipy-1.6.1
```python
from scipy.optimize import curve_fit
```
```python
# first values
x0 = star0.shape[1]/2
y0 = star0.shape[0]/2
a0 = star0.max()-star0.min()
sigma0 = 1
c0 = star0.min()
# x and y
x = np.arange(start=0, stop=star0.shape[1], step=1)
y = np.arange(start=0, stop=star0.shape[0], step=1)
x, y = np.meshgrid(x, y)
#bg = np.percentile(star0,4)
#imgscaled
#img_scaled = np.clip((star0 - bg) / (star0.max() - bg),0,1)
# fit perform
popt, pcov = curve_fit(gaussian2d, (x,y), star0.ravel(), p0=[x0,y0,a0,sigma0,c0])
```
```python
fig, ax = plt.subplots(figsize=(10,10))
ax.imshow(star0, cmap="gray")
data_fitted = gaussian2d((x, y), *popt)
ax.contour(x,y, data_fitted.reshape(star0.shape[0], star0.shape[1]), 8, colors="w")
#plt.colorbar()
#ax.legend()
```
<matplotlib.contour.QuadContourSet at 0x7f6c4489af60>
![png](output_27_1.png)
Las líneas circulares blancas muestran el ajuste a la función Gaussiana 2D
### Trying to get more stars using OpenCV
A partir que aquí no pude acabar el resto de la tarea :(, posiblemente lo complete luego
```python
plt.figure()
plt.hist(im_gray, bins=range(256), edgecolor='none')
plt.title("histogram")
plt.xlim(0,255)
```
(0.0, 255.0)
![png](output_30_1.png)
```python
immean = im_gray.mean()
imstd = im_gray.std()
immean, imstd
```
(59.147874704552464, 38.03617366139822)
```python
import cv2
```
```python
_, t2 = cv2.threshold(im_gray, immean + 3*imstd, 255,0)
type(t2)
```
numpy.ndarray
```python
t2
```
array([[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]], dtype=uint8)
```python
imshow(t2, (10,8), 'gray')
```
![png](output_35_0.png)
```python
contours, hierarchy = cv2.findContours(t2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
```
```python
len(contours)
```
143
```python
plt.figure(figsize=(15,12))
plt.imshow(cv2.drawContours(image, contours,-1,(255,0,0),2))
```
<matplotlib.image.AxesImage at 0x7f6c45e3e1d0>
![png](output_38_1.png)
### OBS
SE pudieron identificar algunas estrellas pero el radio de la región de interés no abarcaba todo el brillo de la estrella. Hasta aquí falta hallar el centro de cada región de interés y el radio aproximado de esta para definir un cuadrado de la imágena recortar.
```python
centers = np.zeros(len(contours))*np.nan
for ct in contours:
m = cv2.moments(ct)
cx = int(m["m10"] / m["m00"])
cy = int(m["m01"] / m["m00"])
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-46-9c20a69bd218> in <module>
----> 1 contours.shape
AttributeError: 'list' object has no attribute 'shape'
output_15_1.png

466 KiB

output_17_0.png

185 KiB

output_20_0.png

11.9 KiB

output_21_1.png

7.13 KiB

output_27_1.png

62.6 KiB

output_30_1.png

5.37 KiB

output_35_0.png

9.2 KiB

output_38_1.png

587 KiB

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment