如何在 python 中根据像素的 rgb 值合并图像中的像素?



到目前为止,我已经将图像划分为特定大小的块,这些块具有原始块的平均颜色。现在,我必须根据它们的相似性合并这些块,其中每个块包含一个像素值(平均颜色值(。为此,我一直在尝试根据图像的 rgb 值合并图像中的像素。到目前为止,我还没有找到任何可以帮助我的东西。所以请帮我解决这个问题。到目前为止我做了什么...

x 和 y 是块大小。这里 x=y=16。

输入:原始图像 输出:处理后的图像 在此之后我没有实施任何内容,因为我不知道如何进一步进行。现在,我必须根据像素的相似性对处理后的图像中的像素进行分组。

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)

您已经使用了相当多的代码来完成第一步,但是,在 2-3 行代码中使用 numpy 函数可以实现相同的输出,如下所示:

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)

我的代码可能不是最佳的,但它工作得很好。

import cv2
import numpy as np
import scipy.misc as smp
import os

l=[]   
res = np.zeros( (256,256,3), dtype=np.uint8 )
while(m<=256):
while(n<=256):
l=image[i:m,j:n][0][0]
low=np.array([l[0] - thresh, l[1] - thresh, l[2] - thresh])
high=np.array([l[0] + thresh, l[1] + thresh, l[2] + thresh])
mask1=cv2.inRange(image,low,high)
res = cv2.bitwise_and(image, image, mask = mask1)
block=0
a=i
b=j
c=m
d=n
k=[]
b=b+x
d=d+x
while(b<256 and d<256):
k=res[a:c,b:d][0][0]
black=[0,0,0]
while((k!=black).all() and b<256 and d<256):
block=block+1
b=b+x
d=d+x
k=res[a:c,b:d][0][0]
image[i:m,j+x:(n+((block)*x))]=l
break
j=j+x
n=n+y
i=i+x
m=m+y
j=0
n=x
image= cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
img = smp.toimage( image )
data1 = np.asarray( img, dtype="int32" )
cv2.imwrite(os.path.join('G:/AI package/datasets/btob/',filename),data1)

最新更新