到目前为止,我已将图像分成特定大小的 block ,这些 block 具有原始 block 的平均颜色。现在,我必须根据它们的相似性合并这些 block ,其中每个 block 包含一个像素值(平均颜色值)。为此,我一直在尝试根据 rgb 值合并图像中的像素。到目前为止,我还没有找到任何可以帮助我解决这个问题的东西。所以请帮我解决这个问题。到目前为止我做了什么......
x 和 y 是 block 大小。这里 x=y=16。
输入:Original Image 输出:Processed image 在此之后我没有实现任何东西,因为我不知道如何进一步进行。现在,我必须根据像素的相似性对处理过的图像中的像素进行分组。
i=0
j=0
m=16
n=16
l=[]
data = np.zeros( (256,256,3), dtype=np.uint8 )
while(m<=256):
while(n<=256):
l=image[i:m,j:n]
print(l)
r=0
g=0
b=0
for q in range(len(l)):
for w in range(len(l)):
r=r+l[q][w][0]
g=g+l[q][w][1]
b=b+l[q][w][2]
r=r/(x*y)
b=b/(x*y)
g=g/(x*y)
k=[r,g,b]
data[i:m,j:n]=k
j=j+16
n=n+16
i=i+16
m=m+16
j=0
n=16
img = smp.toimage( data )
data1 = np.asarray( img, dtype="int32" )
cv2.imwrite(os.path.join('G:/AI package/datasets/_normalized',filename),data1)
最佳答案
您已经使用了很多代码来完成第一步,但是,使用 numpy 函数可以在 2-3 行代码内实现相同的输出:
import cv2
import numpy as np
def get_mean_color(box):
return int(np.mean(box[:, :, 0])), int(np.mean(box[:, :, 1])), int(np.mean(box[:, :, 2]))
def get_super_square_pixels(img, super_pix_width):
height, width, ch = img.shape
if height % super_pix_width != 0:
raise Exception("height must be multiple of super pixel width")
if width % super_pix_width != 0:
raise Exception("width must be multiple of super pixel width")
output_img = np.zeros(img.shape, np.uint8)
for i in xrange(height / super_pix_width):
for j in xrange(width / super_pix_width):
src_box = img[i * super_pix_width:(i + 1) * super_pix_width, j * super_pix_width:(j + 1) * super_pix_width]
mean_val = get_mean_color(src_box)
output_img[i * super_pix_width:(i + 1) * super_pix_width, j * super_pix_width:(j + 1) * super_pix_width] = mean_val
return output_img
img = cv2.imread("/path/to/your/img.jpg")
out = get_super_square_pixels(img, 16)
关于python - 如何根据 python 中的 rgb 值合并图像中的像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733998/