Python 放大图像(无外部库帮助)

Python upscaling an image (no external library help)

我正在尝试将图像放大 200%,但输出图像上有一些奇怪的条。我认为它与中心像素有关。我试图在没有诸如 resize() 之类的库函数的情况下做到这一点。作为参考,我正在尝试实现此功能:

import numpy as np

img = cv2.imread('C:\Users\usama\Downloads\lena.tiff',0)             # Open Image in grayscale
origImg = np.asarray(img)                   # Convert Image to 2D Array
upscaledImg = np.zeros((1024,1024))         # Empty Array for upscaled Image

rowOld = 0            # Orignal Image Row
rowNew = 0            # Upscaled Image Row
colOld = 0            # Original Image Column
colNew = 0            # Upscaled Image Column

def pixeltop():
    return int(origImg[rowOld][colOld]) / 2 + int(origImg[rowOld][colOld + 1]) / 2

def pixelcenter():
    return (int(origImg[rowOld+1][colOld]) + int(origImg[rowOld+1][colOld + 1]) + int(origImg[rowOld+1][colOld]) + int(origImg[rowOld][colOld + 1]))/5

def pixelleft():
    return int(origImg[rowOld][colOld]) / 2 + int(origImg[rowOld + 1][colOld]) / 2

def pixelright():
    return int(origImg[rowOld][colOld + 1]) / 2 + int(origImg[rowOld + 1][colOld + 1]) / 2

def pixelbottom():
    return int(origImg[rowOld + 1][colOld]) / 2 + int(origImg[rowOld + 1][colOld + 1]) / 2

while rowOld < (len(origImg)):                # Outer Loop for transversing rows
  colOld = 0
  colNew = 0
  while colOld < (len(origImg)):              # Inner Loop for transversing columns
    upscaledImg[rowNew][colNew] = origImg[rowOld][colOld]
    upscaledImg[rowNew][colNew+1] = pixeltop()
    upscaledImg[rowNew][colNew+2] = origImg[rowOld][colOld+1]
    upscaledImg[rowNew+1][colNew] = pixelleft()
    upscaledImg[rowNew+1][colNew+1] = pixelcenter()
    upscaledImg[rowNew+1][colNew+2] = pixelright()
    upscaledImg[rowNew+2][colNew] = origImg[rowOld+1][colOld]
    upscaledImg[rowNew+2][colNew+1] = pixelbottom()
    upscaledImg[rowNew+2][colNew+2] = origImg[rowOld+1][colOld+1]
    colOld +=2
    colNew +=4

    if(rowOld == 511):
      break
  rowOld += 2
  rowNew += 4

cv2.imwrite('upscaled.png',upscaledImg)

输出:

新图像是通过修改 3x3 像素的 windows 构建的,但是您的 window 移动 4 像素 x 4 像素,留下一个像素的间隙,因此出现黑条。

仅关注行的示例:

我们从 rownew=0 开始

-> Img[0] 已设置

-> Img[0+1] 已设置

->img[0+2] 已设置

现在 rownew+=4

-> Img[4+0] 已设置

->Img[4+1] 已设置

->Img[4+2] 已设置

将 Img[3] 留空

您可以将 window 的填充更改为 3 或实施分配以具有 4x4 window