我实际上是在做一个图像分发项目,我对图像处理很陌生。我的目标是编写一个程序,将其分成6个部分,每个部分都有相同的像素数据。我写了下面提到的代码。
from PIL import Image
import cv2
im = Image.open('grey.jpg')
im_grey = im.convert('LA')
width,height = im.size
line = []
j,h,total,c=0,0,0,0
for i in range(0,width):
for j in range(0,height):
total += im_grey.getpixel((i,j))[0]
h += im_grey.getpixel((i,j))[0]
c += 1
if c==5:
line.append(h)
c = 0
print "LINE : " + str(i) + "=" + str(h)
h = 0
average_pix = total/6
print total
i,m,j,=0,0,0,
def image_distribution():
global i,m,j,d,average_pix,image
while i<=len(line)-1:
j=j+ line[i]
if j>=average_pix :
img=im.crop((0,m,width,i*5))
img.save("Images/"+"image"+str(i)+".jpg")
m = i*5
j=0
i+=1
image_distribution() 代码似乎工作,但不正确,所以我会非常感激,如果有人可以帮助我的脚本或任何更好的脚本,以同样的目的。我也在尝试写一个高效的程序。谢谢,是的,图像"grey.jpg“是一个灰度图像。
发布于 2017-07-20 18:57:53
在我们的讨论中,您希望将您的图像分解为6个单独的图像。6幅图像的总总和强度相等。由于您对如何分解图像没有偏好,所以我将按列对图像进行分解。因此,每幅图像将有相同的行数,但列数将不同,使得每个分解后的图像的强度之和大致相同。但是,请注意,由于该算法的本质,我们可能不会得到每个图像的完全相同的和,但希望差异是最小的。
因为您可以使用Python中的任何模块,所以我建议您使用NumPy,但是您仍然可以使用Pillow来读取原始图像。首先将图像转换为NumPy数组,这样我们就可以完全使用NumPy数组方法来做您想做的事情。
我将遵循的过程非常简单。
不加进一步的限制:
from PIL import Image
import numpy as np
# Open up the image and convert to grayscale
im = Image.open('grey.jpg').convert('L')
# Convert to a numpy array, convert to floating point for precision
im = np.asarray(im, dtype=np.float)
# Determine the total sum of the pixels
total_sum = im.sum()
# Determine the split point
split_point = int(total_sum / 6)
# Store the images here
data = []
# Counts up how many images we've made so far
count = 0
# Records the column sum
column_sum = 0
# Records beginning coordinate of the split image
x = 0
# Until we've exhausted all of the data...
# Go through each column and determine the cumulative sums
for i in range(im.shape[1]):
column_sum += np.sum(im[:, i])
# If the column sum has passed the threshold
if column_sum >= split_point:
# Get the image and save it
data.append(im[:, x : i + 1])
# Update the variables for the next round
x = i + 1
column_sum = 0
count += 1
# If we have reached the 5th image, just use the rest
# of the image data as the last image
if count == 5:
data.append(im[:, x:])
break
# Save the images now
for (i, split_img) in enumerate(data):
pimg = Image.fromarray(split_img.astype(np.uint8))
pimg.save("image%d.jpg" % (i + 1)) 请注意,最后的复杂之处在于,我们首先将分割的图像转换为uint8,然后创建一个枕头映像,然后将其保存到文件中。图像被标记为imagex.jpg,其中x是从1到6之间的一个数字。
https://stackoverflow.com/questions/45221398
复制相似问题