How to change all colors to transparent but one? - wand

Using the Wand 0.6.2 library I try to remove all colors but one, I got to the desired result using ImageMagick by:
imageMagicCmd = ["magick.exe", "can.jpg",
"-alpha","Set", "(", "+clone", "-fuzz", "40%", "-transparent", "rgb(255,0,0)", ")",
"-compose", "DstOut", "-composite", "SingleColor_Red.png"]
subprocess.call(imageMagicCmd)
can.jpg image:
SingleColor_Red.png image:
How can I achieve the same result using the Wand library?

Try the following...
from wand.image import Image
with Image(filename="can.jpg") as img:
img.alpha_channel = 'set'
f = int(img.quantum_range * 0.4)
img.transparent_color('#f00', 0.0, fuzz=f, invert=True)
img.save(filename="output.png")
... which should generate the expected results.

Related

Plotly express boxplot image export - part of box colors missing in svg file

I have made a boxplot using plotly express (px.box), and the resulting plot looks good in my Google Chrome / Jupyter browser window. Here is a schreenshot of two randomly selected boxes and they look as I expect.
However, after exporting using pio.write_image, it looks like this (zoomed in):
WHY does it not fill up the whole box after export? What can I do to avoid it? I have tried defining width and height as "size*300" to set the DPI to 300, I have tried with and without "scale" and I have tried to use Orca as image export engine, tried export as .PDF, and updated Plotly (Plotly vers. 5.1.0). Links to comprehensive guides for export of high-quality plotly plots for use as figures in scientific papers also much appreciated, as exporting quality very often not satifying.
A example of the problem can be reproduced with this:
import plotly.express as px
import plotly.io as pio
import pandas as pd import plotly.graph_objs as go import sys import plotly
pio.templates.default = “simple_white”
x = [‘Cat1’, ‘Cat1’,‘Cat2’, ‘Cat2’, ‘Cat3’, ‘Cat3’, ‘Cat4’, ‘Cat4’,‘Cat5’, ‘Cat5’, ‘Cat6’, ‘Cat6’, ‘Cat6’, ‘Cat7’, ‘Cat7’, ‘Cat8’, ‘Cat8’,‘Cat11’, ‘Cat11’, ‘Cat12’,‘Cat12’, ‘Cat10’, ‘Cat10’, ‘Cat9’, ‘Cat9’, ‘Cat13’, ‘Cat13’, ‘Cat14’, ‘Cat14’, ‘Cat15’, ‘Cat15’, ‘Cat16’,‘Cat16’, ‘Cat17’]
y = [0.0, 0.0, 0.0, 0.0047, 0.0, 0.036, 0.0, 0.0, 0.12314, 0.02472495, 0.004,0.0, 0.013, 0.0, 0.0, 0.184, 0.056, 0.0186, 0.005928, 0.340, 0.20335, 0.0, 0.0, 0.2481, 0.12, 0.0, 0.0, 0.0201, 0.050, 0.0,0.0, 0.041, 0.0199, 0.0]
data = { “x”: x, “y”: y, }
df = pd.DataFrame(data)
box_plot = px.box(df, x=“x”, y=“y”, points=“all”, width=800, height=400) box_plot.update_yaxes(title=“Random numbers”, title_font=dict(size=18, family=‘Arial’), tickfont=dict(family=‘Arial’, size=18)) box_plot.update_xaxes(title=None, tickangle=45, title_font=dict(size=18, family=‘Arial’), tickfont=dict(family=‘Arial’, size=18), categoryorder=‘array’, categoryarray=[“Cat2”, “Cat1”, “Cat3”,“Cat4”, “Cat5”, “Cat6”, “Cat10”, “Cat11”, “Cat12”,“Cat9”, “Cat8”, “Cat7”, “Cat13”, “Cat14”, “Cat15”,“Cat16”, “Cat17”]) box_plot.update_layout(margin=dict(l = 40, r = 10, t = 10, b = 25), width=1100, height=400, font_family=“Arial”) box_plot.update_traces(boxmean=“sd”, selector=dict(type=‘box’)) box_plot.update_traces(pointpos=-2, selector=dict(type=‘box’)) box_plot.update_traces(marker_symbol=“circle-open”, selector=dict(type=‘box’)) box_plot.show()
pio.write_image(box_plot, r"Boxplot_minimal_work_ex.svg")
I tested first with only two categories, and the export file looked fine! But when I increase the number of categories, it makes the bad quality graph. I wonder if there is an influence from setting the width - so I tried to delete the width and heigth setting from the px.box expression but it gave same bad result.

Converting Images to Numpy arrays with correct dimension

I am trying to convert 100 images into a numpy array, which in turn will be fed into my neural network.
My NN is training data was a 4D numpy array (No of Images, 32, 32, 3).
When using below code to read images and feed into model.predict() i am getting following error.
"Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (100, )"
This is the code i have written:
'''new_data = []
files = glob.glob (r"load images")
for myFile in files:
#print(myFile)
image = cv2.imread(myFile)
new_data.append(np.asarray(image))
#new_data = np.array(new_data)
print('new_data shape:', np.array(new_data).shape)'''
Output is "new_data shape: (100,)"
I am expecting new_data dimention to be (100, 32, 32, 3). Please help on how to achieve this.
Thanks,
Mrinal
Thanks for all the response.The issue was that images were not of same size. After i resized them all to 32*32 and did a np.reshape().
Below is the revised code
files = glob.glob (r"files\*.png*")
for myFile in files:
image = cv2.imread(myFile)
img = cv2.resize(image , (32 , 32)) # Reshaping the testing images to 32*32
new_data.append(img)
new_data = np.reshape(new_data, (len(new_data),32,32,3))
you can directly use PILLOW library for this
from PIL import Image
from numpy import asarray
image = Image.open('kolala.jpeg')
# convert image to numpy array
data = asarray(image)
print(type(data))
print(data.shape)
image2 = Image.fromarray(data)
print(type(image2))

How can I save image without frame in python?

I am plotting image by wavelet coefficients but I don't know how to save it without frame. I tried to do this by plt.savefig but it didn't work.
Any help would be appreciated.
cA5,cD5,cD4,cD3,cD2,cD1=coeffs
for i, ci in enumerate(coeffs):
plt.imshow(ci.reshape(1, -1), extent=[0, 3844, i + 0.5, i + 1.5],cmap='inferno',aspect='auto',interpolation='nearest')
plt.ylim(0.5, len(coeffs) + 0.5)
plt.yticks(range(1, len(coeffs) + 1), ['cA5', 'cD5', 'cD4', 'cD3', 'cD2', 'cD1'])
I understand you want to fit your image. Use plt.axis('off') before plt.savefig
For example, we have the following image.
We can use:
plt.axis('off') remove the axis
plt.savefig("test.png", bbox_inches='tight')
Output:
Code
scale = plt.imread(fname='27BR1.jpg')
plt.axis('off')
plt.imshow(scale, interpolation='nearest')
plt.savefig("test.png", bbox_inches='tight')
Possible Question: There is still a white area under the background?
Answer: Then you can use opencv
import cv2
img = cv2.imread('27BR1.jpg')
cv2.imwrite("test.png", img)
Output:

The best way to set the opacity of an image in Wand?

What is the best way to set the opacity of an image in Wand?
I'm using the most recent versions of ImageMagick (7.0.8-27 Q16 x64 2019-02-09) and Wand (0.5.1) on a Windows 7 computer.
I don't want to use transparent_color().
I want to set the alpha channel of an image for alpha-blended overlaying or compositing.
transparentize() does not set the opacity of an image. It merely darkens the image.
I've tried the following code, but it produced an error.
from wand.image import Image, CHANNELS
from wand.api import library
imageOverlay = Image(filename='mona-lisa.png')
imageOverlay.alpha_channel = 'opaque'
library.MagickSetImageOpacity(imageOverlay.wand, 0.2)
imageOverlay.save(filename='test_transparency.png')
library.MagickSetImageOpacity(wand_imageOverlay.wand, 0.2) TypeError:
'NoneType' object is not callable
I've also tried the following code, but it produced an error.
from wand.image import Image, CHANNELS
from wand.api import library
imageOverlay = Image(filename='mona-lisa.png')
imageOverlay.alpha_channel = 'opaque'
library.MagickEvaluateImage(imageOverlay.wand, 'multiply', 0.2, CHANNELS['alpha'])
imageOverlay.save(filename='test_transparency.png')
library.MagickEvaluateImage(wand_imageOverlay.wand, 'multiply', 0.2,
CHANNEL S['alpha']) ctypes.ArgumentError: argument 2: : wrong type
In Wand, what's the most compact code for setting every alpha-channel pixel to a certain value (e.g. 0.2)?
Thanks to fmw42's comment, now I have a block of Wand code for uniformly setting the pixel values of the alpha channel.
from wand.image import Image
imageOverlay = Image(filename='mona-lisa.png')
imageOverlay.alpha_channel = True
imageOverlay.evaluate(operator='set', value=imageOverlay.quantum_range*0.2, channel='alpha')
imageOverlay.save(filename='test_transparency.png')
The question has been answered.

Add a rectangle to the image using image magic

Good day.
How to impose white_rectangle.jpg on logo.jpg in the image below
using Imagemagic.
And a bonus question: what's Ruby's method can make the task.
def (path_to_image)
# impose white_rectangle.jpg on logo
end
This can easily be accomplished using RMagick:
require 'RMagick'
logo = Magick::Image.read("logo.jpg").first
rect = Magick::Image.read("white_rectangle.jpg").first
result = logo.composite(rect, x, y, Magick::CopyCompositeOp)
result.write "result.jpg"
An alternative is to just draw a white rectangle without using a composite image:
image = Magick::Image.read("logo.jpg").first
gc = Magick::Draw.new
gc.stroke = 'white'
gc.fill = 'white'
gc.rectangle x_start, y_start, x_end, y_end
gc.draw(image)
image.write "result.jpg"
Using ImageMagick command line tools, you can overlay one image with another like this:
$ composite white_rectangle.jpg logo.jpg -geometry +x+y result.jpg

Resources