Блендинг изображений — различия между версиями

Материал из Викиконспекты
Перейти к: навигация, поиск
(Пуассон)
(Пуассон)
Строка 7: Строка 7:
 
Простая вставка одного изображения поверх другого нередко влечет заметный перепад яркости на границе вставки. Метод Пуассона заключается в сглаживании этого перепада с целью сделать дефект менее заметным, используя градиент вставляемого изображения и значения пикселей фонового изображения на границе вставки.
 
Простая вставка одного изображения поверх другого нередко влечет заметный перепад яркости на границе вставки. Метод Пуассона заключается в сглаживании этого перепада с целью сделать дефект менее заметным, используя градиент вставляемого изображения и значения пикселей фонового изображения на границе вставки.
  
Для RGB изображений задача минимизации решается для каждого цветового канала отдельно.
+
todo Note: Для RGB изображений задача минимизации решается для каждого цветового канала отдельно.
  
 
Давайте обозначим за $A$ изображение, которое служит фоном, а за $B$ {{---}} изображение, вставляемое поверх $A$.
 
Давайте обозначим за $A$ изображение, которое служит фоном, а за $B$ {{---}} изображение, вставляемое поверх $A$.
Строка 33: Строка 33:
 
Заметим, что метод Пуассона сдвигает цвета накладываемого изображения и сохраняет свойства градиента (прям всегда? нужно подумоть), туду
 
Заметим, что метод Пуассона сдвигает цвета накладываемого изображения и сохраняет свойства градиента (прям всегда? нужно подумоть), туду
  
 +
 +
Poisson blending для самых маленьких
 +
 +
https://erkaman.github.io/posts/poisson_blending.html
  
 
Another thing that we wish to remark is that even though poisson blending shifts the color of the source image, it still preserves the features of it. In the original source image, f4 is smaller than f3, f5 is greater than f4, and so on, and this also applies to our recovered image. This information was encoded by the gradients of the source image. However, it is also important to realize that poisson blending does not exactly preserve the gradients. In the recovered image, the gradient f3,4 assumes the value 7−4=3, but it was 26−22=4 in the original source image. In the previous section, the gradients of the recovered image were identical to the gradients of the original image. But with poisson blending, the gradients of a completely different image are pasted into another image, and the result of this is that the solver is not always able to recover an image whose gradients exactly match the specified gradients. But the solver tries to find an image whose gradients match as close as possible, and in practice, poisson blending yields good results, which we shall show examples of in the following section.
 
Another thing that we wish to remark is that even though poisson blending shifts the color of the source image, it still preserves the features of it. In the original source image, f4 is smaller than f3, f5 is greater than f4, and so on, and this also applies to our recovered image. This information was encoded by the gradients of the source image. However, it is also important to realize that poisson blending does not exactly preserve the gradients. In the recovered image, the gradient f3,4 assumes the value 7−4=3, but it was 26−22=4 in the original source image. In the previous section, the gradients of the recovered image were identical to the gradients of the original image. But with poisson blending, the gradients of a completely different image are pasted into another image, and the result of this is that the solver is not always able to recover an image whose gradients exactly match the specified gradients. But the solver tries to find an image whose gradients match as close as possible, and in practice, poisson blending yields good results, which we shall show examples of in the following section.

Версия 19:29, 3 января 2021

Определение:
Блендингом изображений (англ. image blending) называют метод, позволяющий наложить часть одного изображения поверх другого таким образом, чтобы композиция изображений выглядела естественно, без швов на границах вставки.
  • картинка*

Пуассон

Простая вставка одного изображения поверх другого нередко влечет заметный перепад яркости на границе вставки. Метод Пуассона заключается в сглаживании этого перепада с целью сделать дефект менее заметным, используя градиент вставляемого изображения и значения пикселей фонового изображения на границе вставки.

todo Note: Для RGB изображений задача минимизации решается для каждого цветового канала отдельно.

Давайте обозначим за $A$ изображение, которое служит фоном, а за $B$ — изображение, вставляемое поверх $A$.

Пусть $p$ — координаты пикселя двухмерного изображения (т.е. $(x, y)$). $A_p$ — значения пикселя фонового изображение, $B_p$ — значение пикселя вставляемого изображения. Пусть $\Omega$ — множество координат $p$, на которых определено вставляемое изображение $B$. $\partial \Omega$ — координаты границы вставляемой области.

Пусть $N_p$ — множество соседей $p$ (максимум четыре пикселя, имеющих общую границу с $p$, т.е. пиксели со следующими координатами: $(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)$). Для всех пар $<p, q>$ таких, что $q \in N_p$, введем $v_{pq} = B_p - B_q$

Обозначим результат блендинга за $O$. Для того чтобы найти значение пикселей в месте наложения $B$, решаем задачу минимизации:

$\underset{f_p,\; p \in \Omega}{\mathrm{min}}\; \underset{p, q \in \Omega}{\sum}\; (O_p - O_q - v_{pq})^2$, где $O_p = A_p$ для $p \in \partial \Omega$

Заметим, что функция, которую мы хотим минимизировать, квадратична относительно переменных $O_p, p \in \Omega$. Для решения задачи минимизации вычислим частные производные по этим переменным и найдем значения переменных, при которых частные производные будут равны нулю.

Для $p \in \Omega$: $\frac{\partial{\underset{p, q \in \Omega}{\sum}\; (O_p - O_q - v_{pq})^2}}{\partial O_p} = \underset{q \in N_p}{\sum} 2 (O_p - O_q - v_{pq}) - \underset{q \in N_p}{\sum} 2 (O_q - O_p - v_{qp}) = 2 \underset{q \in N_p}{\sum} 2 (O_p - O_q - v_{pq})$.

Приравнивая к нулю, получаем: $|N_p| O_p - \underset{q \in N_p}{\sum} O_q = \underset{q \in N_p}{\sum} v_{pq}$.

Для точек, граничащих с $\partial \Omega$: $|N_p| O_p - \underset{q \in N_p \cap \Omega}{\sum} O_q = \underset{q \in N_p \cap \partial \Omega}{\sum} A_q + \underset{q \in N_p}{\sum} v_{pq}$.

Решаем систему уравнений и получаем значения $O_p$ для $p \in \Omega$.

todo: Поскольку система уравнений sparse symmetric positive-defined, можно использовать следующие итеративные алгоритмы: Gauss-Seidel, V-cycle multigrid.

Заметим, что метод Пуассона сдвигает цвета накладываемого изображения и сохраняет свойства градиента (прям всегда? нужно подумоть), туду


Poisson blending для самых маленьких

https://erkaman.github.io/posts/poisson_blending.html

Another thing that we wish to remark is that even though poisson blending shifts the color of the source image, it still preserves the features of it. In the original source image, f4 is smaller than f3, f5 is greater than f4, and so on, and this also applies to our recovered image. This information was encoded by the gradients of the source image. However, it is also important to realize that poisson blending does not exactly preserve the gradients. In the recovered image, the gradient f3,4 assumes the value 7−4=3, but it was 26−22=4 in the original source image. In the previous section, the gradients of the recovered image were identical to the gradients of the original image. But with poisson blending, the gradients of a completely different image are pasted into another image, and the result of this is that the solver is not always able to recover an image whose gradients exactly match the specified gradients. But the solver tries to find an image whose gradients match as close as possible, and in practice, poisson blending yields good results, which we shall show examples of in the following section.

Глубокий блендинг

Гармонизация

 fun Harmonization(
   I,   // Входное изображение 
   M,   // Маска 
   S    // Стилевое изображение 
 ):
     // Тут будет комментарий 
   I' := SinglePassHarmonization(I, M, S, IndependentMapping)
     // Тут тоже 
   O  := SinglePassHarmonization(I', M, S, ConsistentMapping)
   return O
 fun SinglePassHarmonization(
   I,   // Входное изображение 
   M,   // Маска 
   S,   // Стилевое изображение 
   $\pi$   // Neural mapping function todo: translate this shit 
 ):
   F_I := ComputeNeuralActivations(I)
   F_S := ComputeNeuralActivations(S)
   P := $\pi$(F_I, M, F_S)
   O := Reconstruct(I, M, S, P)

   return O