最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Error when converting image to array and back to image in python, image is erased. How do I get circle back, not a straight line

programmeradmin5浏览0评论

When I run this code, from original image (blue ring attached), at first show I see circle but after if I convert to RGB and do any manipulation(I tried selecting different columns, etc.), I always get a straight line (hopefully attached here too). Eventually I would like to be able to manipulate RGB channels, but for now just display every color channel as same matrix as original blue channel.

[

Code is:

from PIL import Image
import numpy as np

img = Image.open(r"test.jpg") # creating image object
img1 = img.convert("RGB") # using convert method for img1
img1.show()


def magColBlue(x):
    x=np.array(x)
    print("x first shape is ", np.shape(x))
    x=x[:,:,0]
    print("x 2nd shape is ", np.shape(x))
    print(x)
    return x



blueAmount =magColBlue(img1)
print("blue shape",np.shape(blueAmount))
imgBlue = Image.fromarray(np.asarray([blueAmount,blueAmount,blueAmount]), 'RGB')
imgBlue.show()

When I run this code, from original image (blue ring attached), at first show I see circle but after if I convert to RGB and do any manipulation(I tried selecting different columns, etc.), I always get a straight line (hopefully attached here too). Eventually I would like to be able to manipulate RGB channels, but for now just display every color channel as same matrix as original blue channel.

[

Code is:

from PIL import Image
import numpy as np

img = Image.open(r"test.jpg") # creating image object
img1 = img.convert("RGB") # using convert method for img1
img1.show()


def magColBlue(x):
    x=np.array(x)
    print("x first shape is ", np.shape(x))
    x=x[:,:,0]
    print("x 2nd shape is ", np.shape(x))
    print(x)
    return x



blueAmount =magColBlue(img1)
print("blue shape",np.shape(blueAmount))
imgBlue = Image.fromarray(np.asarray([blueAmount,blueAmount,blueAmount]), 'RGB')
imgBlue.show()
Share edited Mar 11 at 14:24 Christoph Rackwitz 15.9k5 gold badges39 silver badges51 bronze badges asked Mar 10 at 20:57 Gad11ngGad11ng 231 silver badge6 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

I believe the issue lies in the following line:

Image.fromarray(np.asarray([blueAmount,blueAmount,blueAmount])

The numpy array you use here would have shape (3, x, y) rather than (x, y, 3) which may have been your intention.

Instead of

np.asarray([blueAmount,blueAmount,blueAmount])

you should use

np.dstack([blueAmount, blueAmount, blueAmount])

or np.stack() with axis=2 argument.

That will have the right order of dimensions.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论