Auto threshold in ImageJ/FIJI with Python - python

I'm trying to write python scripts in ImageJ and I'm having problems with autothresholding. It won't let me use the IJ.setAutoThreshold("Default dark"). An example bit of code is below (with a few things left out for clarity):
from ij import IJ, ImagePlus
from java.lang import Runtime, Runnable
import os
for i in filepaths: #filepaths being the files I'm opening
IJ.open(i)
IJ.run("Split Channels") #this is splitting a two channel image
imp = IJ.getImage()
imp.close() #this is closing the channel I don't want
IJ.setAutoThreshold("Default dark") #this is trying to set a threshold
Setting the auto threshold here gives
AttributeError: type object 'ij.IJ' has no attribute 'setAutoTrheshold'
How can I access ImageJ's threshold function?
Cheers!

Have a look at the javadoc: IJ has a method taking two arguments
setAutoThreshold(ImagePlus imp, String method)
so in your case
IJ.setAutoThreshold(imp, "Default dark")
should work.

Related

How to call up Open CV Durand Tonemap function?

I'm trying to examine multiple tone-mapping operators in Open CV, using Python.
Various sources use four operators (Drago, Durand, Reinhard, Mantiuk). Three of them work. However, when I call up cv2.createTonemapDurand(), I get this error:
AttributeError: module 'cv2.cv2' has no attribute 'createTonemapDurand'
Is it possible to call the Durand operator somehow, or did Open CV drop that one recently?
Thanks!
I'll switch from comment to answer to have a better representation.
you just have to :
import cv2
cv2.xphoto.createTonemapDurand()
Be aware that, if u compiled opencv by yourself, you had to check OPENCV_ENABLE_NONFREE.
Please post your code where you import cv2 and call the function. If you want to look for some functions, attributes or whatever either look in the documentation of the package or use dir() and type(). For your example you can use this:
import cv2
from re import match
cv2_filtered = filter(lambda v: match('.*Tonemap', v), dir(cv2))
[print(val) for val in cv2_filtered]
Returns:
Tonemap
TonemapDrago
TonemapMantiuk
TonemapReinhard
createTonemap
createTonemapDrago
createTonemapMantiuk
createTonemapReinhard
Seems like there is no function createTonemapDurand in cv2.

TypeError calling python function using chaquopy

I have a python file which has many 'def' values in it. When I try to integrate the python file with android studio, I get a type error. The input is a image file and I want the lowerRange and upperRange to be based on that image, so I cannot define a value to them, since image size can vary everytime.
import numpy as np
import cv2
import os
import matplotlib.pyplot as plt
from PIL import Image
def host(croppedImage,lowerRange, upperRange):
mask_yellow = cv2.inRange(croppedImage,lowerRange,upperRange)
dilatation_type = cv2.MORPH_RECT
dilatation_size = 1
element = cv2.getStructuringElement(dilatation_type, (dilatation_size + 2, dilatation_size+2), (dilatation_size, dilatation_size))
dilated_mask_image = cv2.dilate(mask_yellow, element)
return dilated_mask_image
def DrawContourRect(contour):
rect = cv2.minAreaRect(contour)
return cv2.boxPoints(rect)
-----------------------------This is just a part of code---------------------------------
And this is the xml code for python object:
PyObject pyo = py.getModule("file");
PyObject obj = pyo.callAttr("host", imageString);
And the error is this:
com.chaquo.python.PyException: TypeError: detect() missing 2 required positional arguments: 'lowerRange' and 'upperRange'
at <python>.chaquopy_java.call(chaquopy_java.pyx:285)
at <python>.chaquopy_java.Java_com_chaquo_python_PyObject_callAttrThrows(chaquopy_java.pyx:257)
Is there any way to solve this problem and how can the chaquopy read each and every 'def' value (host and DrawContourRect.
The error message and code don't seem to match, but I assume that host and detect are either the same function, or that they have the same signature.
If that's correct, then the problem is simply that you're passing 1 argument to a function that requires 3. If you want the lowerRange and upperRange to be based on the image, then you'll have to either:
Calculate them on the Java side and pass them to Python using the 2 extra arguments; OR
Remove the 2 extra arguments from the function, and calculate the range on the Python side.

VSCode Itellisense with python C extension module (petsc4py)

I'm currently using a python module called petsc4py (https://pypi.org/project/petsc4py/). My main issue is that none of the typical intellisense features seems to work with this module.
I'm guessing it might have something to do with it being a C extension module, but I am not sure exactly why this happens. I initially thought that intellisense was unable to look inside ".so" files, but it seems that numpy is able to do this with the array object, which in my case is inside a file called multiarray.cpython-37m-x86_64-linux-gnu (check example below).
Does anyone know why I see this behaviour in the petsc4py module. Is there anything that I (or the developers of petsc4py) can do to get intellisense to work?
Example:
import sys
import petsc4py
petsc4py.init(sys.argv)
from petsc4py import PETSc
x_p = PETSc.Vec().create()
x_p.setSizes(10)
x_p.setFromOptions()
u_p = x_p.duplicate()
import numpy as np
x_n = np.array([1,2,3])
u_n = x_n.copy()
In this example, when trying to work with a Vec object from petsc4py, doing u_p.duplicate() cannot find the function and the suggestion is simply a repetition of the function immediately before. However, using an array from numpy, doing u_n.copy() works perfectly.
If you're compiling in-place then you're bumping up against https://github.com/microsoft/python-language-server/issues/197.

Python: Converting COM PyIUnknown to known data type

I am currently trying to make a python app do the same thing as a VB app.
The app retrieves an image from an external device over the COM API. I've used win32com and managed to use the Dispatch mechanism to talk with the COM API.
In the VB app, the image is stored like this
pictureData = objResult.Properties('ResultImage')
myImage = AxHost.GetPictureFromIPicture(pictureData)
In my Python app, however on the picture data member, I get PyIUnknown object type. How do I get the image data out of this 'unknown' object?
Let me add that for other 'basic' data like strings, I can see them fine over the Python app.
I found a method that works, maybe not perfect, but if someone Google's this question, I hope it helps.
from win32com.client import Dispatch
import pythoncom
imagedata = data.Properties.Item('ResultImage') #this is samas the VB line in the question , except I have to add 'Item' here
#win32com does not define IPicture type (http://timgolden.me.uk/pywin32-docs/com_objects.html)
ipicture = Dispatch(imagedata.QueryInterface(pythoncom.IID_IDispatch))
import win32ui
import win32gui
#creates a PyCBitMap object
imagebitmap = win32ui.CreateBitmapFromHandle(ipicture.Handle)
#we need a DC handle to save the bitmap file for some reason...
dc_handler = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
#this overwrites any older file without asking
imagebitmap.SaveBitmapFile(dc_handler,'last_pic.bmp')
Questions I still have in my mind are:
are we only forced to interact with IPicture or any non-defined COM (by win32com) in a dynamic way? Is there an elegant way to extend the definitions of interfaces etc.?
I tried using QueryInterface(pythontypes.IID('{7BF80980-BF32-101A-8BBB-00AA00300CAB}'). I got this IID from http://msdn.microsoft.com/en-us/library/windows/desktop/ms680761(v=vs.85).aspx however I got an error within Python that this interface cannot be handled.
Not sure why I cannot use the methods defined for IPicture, but I could access the attributes?
I tried simply to use ipicture.get_Handle() or ipicture.SaveAsFile() but these didn't work.

Pymol not outputting image

I am trying to draw a protein structure from a pdb file using pymol.
However, when I try to run the script below, a pymol window opens but it is just pitch black. Also, bizarrely, the pdb file is outputted to the shell.
Here is my code:
bioservices_pdb_obj = PDB()
pdb_file = bioservices_pdb_obj.getFile(results[str(Brick.part_attrib(self,'uniprot_id'))][detail-1],'pdb')
pdb_name = str(Brick.part_attrib(self,'uniprot_id'))
pymol.finish_launching()
pymol.cmd.load(pdb_file, pdb_name)
pymol.cmd.disable("all")
pymol.cmd.enable(pdb_name)
pymol.cmd.png("my_pdb.png")
pymol.cmd.quit()
Does anyone know what is going on here?
The .png file 'my_pdb' is dumped into the working directory, but that's just black as well.
Does this also happen with any other PDB file? If yes, you can try a workaround using the cmd.mpng() function. You can use this function also in other contexts if the cmd.png() function doesn't work, e.g. when using PyMOL in command-line mode.
import pymol
from pymol import cmd
import os
pymol.finish_launching()
cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image.
def pnghack(filepath, width=1024, height=768):
"""Workaround if cmd.png() doesn't work"""
cmd.viewport(width, height) # Set resolution
cmd.mpng(filepath, 1, 1) # Use batch png mode with 1 frame only
cmd.mplay() # cmd.mpng needs the animation to 'run'
cmd.load(pdb_file, pdb_name)
cmd.disable("all")
cmd.enable(pdb_name)
pnghack("my_pdb.png")
cmd.quit()
Note that the resulting png file is named "my_pdb0001.png" as the cmd.mpng() function always adds the framenumber.

Categories