Home > Enterprise >  Why does this Image averaging just generates vertical lines?
Why does this Image averaging just generates vertical lines?

Time:10-28

I am trying to create a program that averages image's pixel values, but so far it has just generated vertical lines.

This is my code so far:

from typing import List

import cv2 as cv
import numpy as np


def main():
    # Importing two of the same imagae for debugigng purposes
    a = cv.imread("Datasets/OTIS/OTIS_PNG_Gray/Fixed Patterns/Pattern1/Pattern1_001.png", cv.IMREAD_GRAYSCALE)
    b = cv.imread("Datasets/OTIS/OTIS_PNG_Gray/Fixed Patterns/Pattern1/Pattern1_001.png", cv.IMREAD_GRAYSCALE)

    s = [a, b]
    avg = [[0] * len(a[0])] * len(a)
    print(f"rows: {len(a)} cols: {len(a[0])}")
    print(f"rows: {len(avg)} cols: {len(avg[0])}")

    for i in range(len(a)):
        for j in range(len(a[0])):
            # print(f"({i}, {j}): {temp_mean(s, i, j)}")
            avg[i][j] = temp_mean(s, i, j) / 255

    avim = np.array(avg)
    print(f"rows: {len(avim)} cols: {len(avim[0])}")

    cv.imshow("title", avim)

    cv.waitKey(0)


def temp_mean(seq: List[List[List[any]]], i: int, j: int):
    out = 0

    for im in seq:
        out  = im[i][j]

    return out / len(seq)


if __name__ == '__main__':
    main()

Source Image: Source Image

Image generated: Image generated

CodePudding user response:

Most likely your problem is avg being defined as a list of copies of one list. When you update one list (row), you update them all. Thus, the output image has all identical rows.

You really should be using NumPy arrays to represent an image:

avg = np.zeros(a.shape)

CodePudding user response:

The issue here is that avg is a shallow copy of a, created by the * multiplication. This means that avg contains multiple references to the same row in a, so when you update avg[i][j], you're actually modifying a[i][j] as well. The result is that every row of avg ends up containing identical values - the last row of a that you modified. To fix this, create a deep copy of a for avg using: avg = [row[:] for row in a]

This will create a new list for each row, resulting in distinct data that can be modified independently

  • Related