How to display more than one image dynamically with python (pyqt5)? - pyqt5

I'm using python to build an application by PyQt5, the main idea is to display images from a directory and for each image some masks show up next to it to select one of them (i.e. for each image there are different number of masks). So, I want to display these masks in a "container" that can handle this dynamically.
I tried QlistWidget in a scroll area and the masks are displayed as icons in it, but I want to use something else to handle them easier and retrieve any mask as Qpixmap or QImage to use it in another operations without convert it multiple times (which slows down the program)
this is the part that displays the masks (this is the only way that worked with me)
for ann in annotations:
mask = self.coco.annToMask(ann)
mask_img = Image.fromarray((mask*255).astype(np.uint8))
qt_img = ImageQt.ImageQt(mask_img) # convert Image to ImageQt
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(qt_img))
item = QtWidgets.QListWidgetItem(icon, f"{annIndex}")
self.listWidget.addItem(item)
annIndex += 1

Related

How do I resize an array of squished PyQt5 widgets? [duplicate]

I have a QScrollArea Widget, which starts empty;
It has a vertical layout, with a QGridLayout, and a vertical spacer to keep it at the top, and prevent it from stretching over the whole scroll area;
Elsewhere in the program, there is a QTextEdit, which when changed, has its contents scanned for "species" elements, and then they are added to the QGridLayout. Any species elements which have been removed are removed too. This bit works;
I have turned the vertical scrollbar on all the time, so that when it appears it does not sit on top of the other stuff in there. Note that the scroll bar is larger than the scroll box already though, despite not needing to be.
This is the problem. The scroll area seems to be preset, and i cannot change it. If i add more rows to the QGridLayout, the scroll area doesn't increase in size.
Instead, it stays the same size, and squeezes the QGridLayout, making it look ugly (at first);
And then after adding even more it becomes unusable;
Note that again, the scroll bar is still the same size as in previous images. The first two images are from Qt Designer, the subsequent 3 are from the program running.
If I resize the window so that the QScrollArea grows, then I see this:
Indicating that there's some layout inside the scroll area that is not resizing properly.
My question is; what do I need to do to make the scrollable area of the widget resize dynamically as I add and remove from the QGridLayout?
If you're coming here from Google and not having luck with the accepted answer, that's because you're missing the other secret invocation: QScrollArea::setWidget. You must create and explicitly identify a single widget which is to be scrolled. It's not enough to just add the item as a child! Adding multiple items directly to the ScrollArea will also not work.
This script demonstrates a simple working example of QScrollArea:
from PySide.QtGui import *
app = QApplication([])
scroll = QScrollArea()
scroll.setWidgetResizable(True) # CRITICAL
inner = QFrame(scroll)
inner.setLayout(QVBoxLayout())
scroll.setWidget(inner) # CRITICAL
for i in range(40):
b = QPushButton(inner)
b.setText(str(i))
inner.layout().addWidget(b)
scroll.show()
app.exec_()
The documentation provide an answer :
widgetResizable : bool
This property holds whether the scroll area should resize the view widget.
If this property is set to false (the default), the scroll area honors the size of its widget.
Set it to true.
Why don't you use a QListView for your rows, it will manage all the issues for you? Just make sure that after you add it you click on the Class (top right window of designer) and assign a layout or it wont expand properly.
I use a QLIstWidget inside a QScrollArea to make a scrollable image list
Try this for adding other objects to the list, this is how I add an image to the list.
QImage& qim = myclass.getQTImage();
QImage iconImage = copyImageToSquareRegion(qim, ui->display_image->palette().color(QWidget::backgroundRole()));
QListWidgetItem* pItem = new QListWidgetItem(QIcon(QPixmap::fromImage(iconImage)), NULL);
pItem->setData(Qt::UserRole, "thumb" + QString::number(ui->ImageThumbList->count())); // probably not necessary for you
QString strTooltip = "a tooltip"
pItem->setToolTip(strTooltip);
ui->ImageThumbList->addItem(pItem);
Update on Artfunkel's answer:
Here's a PySide6 demo that uses a "Populate" button to run the for loop adding items to the scroll area. Each button will also delete itself when clicked.
from PySide6.QtWidgets import *
app = QApplication([])
scroll = QScrollArea()
scroll.setWidgetResizable(True) # CRITICAL
inner = QFrame(scroll)
inner.setLayout(QVBoxLayout())
scroll.setWidget(inner) # CRITICAL
def on_remove_widget(button):
button.deleteLater()
def populate():
for i in range(40):
b = QPushButton(inner)
b.setText(str(i))
b.clicked.connect(b.deleteLater)
inner.layout().addWidget(b)
b = QPushButton(inner)
b.setText("Populate")
b.clicked.connect(populate)
inner.layout().addWidget(b)
scroll.show()
app.exec()

Remove black values in a modis merge image

the following image shows my actuall result of a merged modis image.
I used pyhdf.SD to open and manipulate and plot the data in a loop. It started on the right upper corner.
The plot is ok... put on some areas overlaped. The easiest way is to remove the black borders.
I wanted to use this:
np.ma.masked_where(rgb_projected==0.,rgb_projected)
rgb_projected is the original rgb matix.
rgb_projected = np.zeros((1000, 1000,3))
rgb_projected[:,:,0] = z_01[:,:]
rgb_projected[:,:,1] = z_02[:,:]
rgb_projected[:,:,2] = z_03[:,:]
rgb_projected.shape
whereAreNaNs = np.isnan(rgb_projected);
rgb_projected[whereAreNaNs] = 0.;
rgb_plot=np.ma.masked_where(rgb_projected==0.,rgb_projected)
The interesting thing is, that everything is True although the first valueas are 0.
Any ideas?

pine script with two indicators one overlaid on the chart and another on its own?

I am trying to write a pine script with two indicators one overlaid on the chart (EMA) and another on its own?(Stoch) I cannot seem to find any info on how to separate these (Visually) but keep them within 1 pine script, ie to be able to take trading decisions based on these.
The earlier answer from Luc is right, unfortunately. Each script can either create plots that are overlaid on the default price chart, or shown in a different pane, but not both. But there is a workaround.
Suppose you've made some non-trivial calculation in your script and you'd like to put it in different pane. E.g. the next code:
//#version=4
study(title="Stochastic", shorttitle="Stoch", format=format.price, precision=2)
periodK = input(14, title="K", minval=1)
periodD = input(3, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
k = sma(stoch(close, high, low, periodK), smoothK)
d = sma(k, periodD)
plot(k, title="%K", color=color.blue)
plot(d, title="%D", color=color.orange)
h0 = hline(80)
h1 = hline(20)
fill(h0, h1, color=color.purple, transp=75)
// This next plot would work best in a separate pane
someNonTrivialCalculatedSeries = close
plot(ema(someNonTrivialCalculatedSeries, 25), title="Exporting Plot")
Because they have different scale, one of them most likely will break another indicator's scale.
So you'd like show Stoch in different pine, whereas ema() should be overlayed with the main chart. For that you should make the next steps:
Turn off in the study's the extra plot to return scale to normal:
Apply to the chart the next script:
//#version=4
study("NonOverlayIndicator", overlay=true)
src = input(defval=close, type=input.source)
plot(src)
Choose in the second's script inputs source required plot from the first script:
And voilà - you got the plots in different pines:
But if you want split the plots because you have retrictions on amount of studies you allowed to apply (e.g. 3 for free-account) - that won't help you.
It cannot be done. A script runs either in overlay=true mode on the chart, in which case it cannot direct plots elsewhere, or in a separate pane when overlay=false (the default).
When the script is running in a pane, it can change the color of the chart bars using barcolor(), but that's the only way it can modify the chart.
It is possible to rescale signals so that multiple bounded (e.g., 0-100, -1 to +1) signals generated by one script appear one on top of the other, but this is typically impossible in overlay mode, as the vertical scale varies with the bars on the chart. The only way for an overlay script to work with its own scale is when it uses No scale, but this prevents the indicator's plots to plot relative to price, and so the chart's bars.
Nice workaround from Michael.
Unfortunately, this only seems to work to pass data for one plot.
I would like to pass data for 3 different plots to the stock price graph.
If I try this, for 'input.source' I can only select the standard sources: "open, high, low, close ...". I can not select the data from other indicators.
If I remove plots 2 and 3, it works as Michael described.
Anybody has a workaround for the workaround..? ;-)

Is It Possible To Use Embedded Resource Images For ObjectListView SubItems

I can't seem to find any information on this, but does anyone know if it is possible to use an embedded image from my.resources within an ObjectListView SubItem?
I am currently using images stored in an ImageList control, but I find for some reason, those images get corrupted and start displaying imperfections. I don't have the problem if I pull them from the embedded resources as I previously have with the normal listview control.
I am using the ImageGetter routine to return a key reference the ImageList, however, ultimately I would like to pull these from embedded resources. I would like to also do this for animated GIF references as well.
If anyone knows a way, could you please assist. Sample code would be appreciated.
Thanks
You can return three different types from the ImageGetter
int - the int value will be used as an index into the image list
String - the string value will be used as a key into the image list
Image - the Image will be drawn directly (only in OwnerDrawn mode)
So option number 3 could be what you want. Note that you have to set objectListView1.OwnerDraw = true.
If that does not work, an alternative could be to load the images into the ImageList at runtime. There is an example here.
this.mainColumn.ImageGetter = delegate(object row) {
String key = this.GetImageKey(row);
if (!this.listView.LargeImageList.Images.ContainsKey(key)) {
Image smallImage = this.GetSmallImageFromStorage(key);
Image largeImage = this.GetLargeImageFromStorage(key);
this.listView.SmallImageList.Images.Add(key, smallImage);
this.listView.LargeImageList.Images.Add(key, largeImage);
}
return key;
};
This dynamically fetches the images if they haven’t been already fetched. You will need to write the GetImageKey(), GetSmallImageFromStorage() and GetLargeImageFromStorage() methods. Their names will probably be different, depending on exactly how you are deciding which image is shown against which model object.

GIMP Script-fu changing default scripts

I am having issues re-writing one of the default logo scripts in GIMP(using Script-fu based on scheme). For one thing the alpha layer is not shown in the layer browser after the image is shown. I am re-writing the Create Neon Logo script(neon-logo.scm) and I want it to do the following before it displays the new image:
add an alpha channel
change black(background color) to transparent via colortoalpha
return the generated image as an object to be used in another python script(using for loops to generate 49 images)
I have tried modifying the following code to the default script:
(gimp-image-undo-disable img)
(apply-neon-logo-effect img tube-layer size bg-color glow-color shadow) *Generates neon logo
(set! end-layer (car (gimp-image-flatten img))) *Flattens image
(gimp-layer-add-alpha end-layer) *Adds alpha layer as last layer in img(img=the image)
(plug-in-colortoalpha img 0 (255 255 255)) *Uses color to alpha-NOT WORKING
(gimp-image-undo-enable img) *Enables undo
(gimp-display-new img) *Displays new image
For number 3 my python code is this:
for str1 in list1:
for color1 in list3:
img = pdb.script_fu_neon_logo(str1,50,"Swis721 BdOul BT",(0,0,0),color1,0)
But img is a "Nonetype" object. I would like to make it so that instead of displaying the generated image in a new window, it just returns the generated image for use with my python script.
Can anyone help?
Maybe to keep everything more managaeable and readable, you should translate theoriginal script into Python - that way you willhaveno surprises on otherwiser trivial things as variable assignment, picking elements from sequences and so on.
1 and 2) your calls are apparantly correct to flaten an "add an alpha channel " (not "alpha layer",a s you write, please) to the image - but you are calling color-to-alpha to make White (255 255 255) transparemt not black. Trey changing that to (0 0 0) - if it does not work, make]
each of the calls individually, either on script-fu console or on python console, and check what is wrong.
3) Script-fu can't return values to the caller (as can be seen by not having a "return value type" parameter to the register call. That means that scripts in scheme in GIMP can only render thigns on themselves and not be used to compose more complex chains.
That leaves you with 2 options: port the original script to Python-fu (and them just register it to return a PF-IMAGE) - or hack around the call like this, in Python:
create a set with all images opened, call your script-fu, check which of your images currently open is not on the set of images previously opened - that will be your new image:
The tricky part with this is that: there is no unique identifier to an image when you see it from Python-fu - so you 'dhave to compose a value like (name, number_of_layers, size) to go on those comparison sets and even that might not suffice - or youg could juggle with "parasites" (arbitrary data that can be attached to an image). As you can see, having the original script-fu rewriten in Python, since all the work is done by PDB calls, and these translate 1:1, is preferable.