Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_plantcv_roi_from_binary_image():
# Test cache directory
cache_dir = os.path.join(TEST_TMPDIR, "test_plantcv_roi_from_binary_image")
os.mkdir(cache_dir)
# Read in test RGB image
rgb_img = cv2.imread(os.path.join(TEST_DATA, TEST_INPUT_COLOR))
# Create a binary image
bin_img = np.zeros(np.shape(rgb_img)[0:2], dtype=np.uint8)
cv2.rectangle(bin_img, (100, 100), (1000, 1000), 255, -1)
# Test with debug = "print"
pcv.params.debug = "print"
pcv.params.debug_outdir = cache_dir
_, _ = pcv.roi.from_binary_image(bin_img=bin_img, img=rgb_img)
# Test with debug = "plot"
pcv.params.debug = "plot"
_, _ = pcv.roi.from_binary_image(bin_img=bin_img, img=rgb_img)
# Test with debug = None
pcv.params.debug = None
roi_contour, roi_hierarchy = pcv.roi.from_binary_image(bin_img=bin_img, img=rgb_img)
# Assert the contours and hierarchy lists contain only the ROI
assert np.shape(roi_contour) == (1, 3600, 1, 2)
def read_data(filename):
"""Read hyperspectral image data from file.
Inputs:
filename = name of image file
Returns:
spectral_array = image object as numpy array
:param filename: str
:return spectral_array: __main__.Spectral_data
"""
# Store debug mode
debug = params.debug
params.debug = None
# Initialize dictionary
header_dict = {}
headername = filename + ".hdr"
with open(headername, "r") as f:
# Replace characters for easier parsing
hdata = f.read()
hdata = hdata.replace(",\n", ",")
hdata = hdata.replace("\n,", ",")
hdata = hdata.replace("{\n", "{")
hdata = hdata.replace("\n}", "}")
hdata = hdata.replace(" \n ", "")
hdata = hdata.replace(";", "")
hdata = hdata.split("\n")
center_v.shape = (20, 1, 2)
img2 = np.copy(img)
for i in top:
x = i[0, 0]
y = i[0, 1]
cv2.circle(img2, (int(x), int(y)), params.line_thickness, (255, 0, 0), -1)
for i in bottom:
x = i[0, 0]
y = i[0, 1]
cv2.circle(img2, (int(x), int(y)), params.line_thickness, (255, 0, 255), -1)
for i in center_v:
x = i[0, 0]
y = i[0, 1]
cv2.circle(img2, (int(x), int(y)), params.line_thickness, (0, 79, 255), -1)
if params.debug == 'plot':
plot_image(img2)
elif params.debug == 'print':
print_image(img2,
os.path.join(params.debug_outdir, (str(params.device) + '_x_axis_pseudolandmarks.png')))
# Store into global measurements
for pt in top:
top_list.append(pt[0].tolist())
for pt in bottom:
bottom_list.append(pt[0].tolist())
for pt in center_v:
center_v_list.append(pt[0].tolist())
outputs.add_observation(variable='top_lmk', trait='top landmark coordinates',
method='plantcv.plantcv.x_axis_pseudolandmarks', scale='none', datatype=tuple,
value=tuple(top_list), label='none')
:param coord: tuple, list
:param radius: int
:param spacing: tuple
:param nrows: int
:param ncols: int
:return mask: numpy.ndarray
"""
# Autoincrement the device counter
params.device += 1
# Initialize ROI list
rois = []
# Store user debug
debug = params.debug
# Temporarily disable debug
params.debug = None
# Get the height and width of the reference image
height, width = np.shape(img)[:2]
# Initialize a binary image of the circle
bin_img = np.zeros((height, width), dtype=np.uint8)
roi_contour = []
roi_hierarchy = []
# Grid of ROIs
if (type(coord) == tuple) and ((nrows and ncols) is not None):
# Loop over each row
for i in range(0, nrows):
# The upper left corner is the y starting coordinate + the ROI offset * the vertical spacing
# Make sure the image is binary
if len(np.shape(bin_img)) != 2 or len(np.unique(bin_img)) != 2:
fatal_error("Image is not binary")
# Cast binary image to boolean
bool_img = bin_img.astype(bool)
# Find and fill contours
bool_img = remove_small_objects(bool_img, size)
# Cast boolean image to binary and make a copy of the binary image for returning
filtered_img = np.copy(bool_img.astype(np.uint8) * 255)
if params.debug == 'print':
print_image(filtered_img, os.path.join(params.debug_outdir, str(params.device) + '_fill' + str(size) + '.png'))
elif params.debug == 'plot':
plot_image(filtered_img, cmap='gray')
return filtered_img
h = label_coord_y[i]
text = "{:.2f}".format(segment_angles[i])
cv2.putText(img=labeled_img, text=text, org=(w, h), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=.55, color=(150, 150, 150), thickness=2)
segment_label = "ID" + str(i)
angle_header.append(segment_label)
angle_data.extend(segment_angles)
if 'morphology_data' not in outputs.measurements:
outputs.measurements['morphology_data'] = {}
outputs.measurements['morphology_data']['segment_angles'] = segment_angles
# Auto-increment device
params.device += 1
if params.debug == 'print':
print_image(labeled_img, os.path.join(params.debug_outdir, str(params.device) + '_segmented_angles.png'))
elif params.debug == 'plot':
plot_image(labeled_img)
return angle_header, angle_data, labeled_img
Returns:
img_gblur = blurred image
:param img: numpy.ndarray
:param ksize: tuple
:param sigmax: int
:param sigmay: str or int
:return img_gblur: numpy.ndarray
"""
img_gblur = cv2.GaussianBlur(img, ksize, sigma_x, sigma_y)
params.device += 1
if params.debug == 'print':
print_image(img_gblur, os.path.join(params.debug_outdir, str(params.device) + '_gaussian_blur.png'))
elif params.debug == 'plot':
if len(np.shape(img_gblur)) == 3:
plot_image(img_gblur)
else:
plot_image(img_gblur, cmap='gray')
return img_gblur
Returns:
eu_length_header = Segment euclidean length data header
eu_length_data = Segment euclidean length data values
labeled_img = Segmented debugging image with lengths labeled
:param segmented_img: numpy.ndarray
:param objects: list
:param hierarchy: numpy.ndarray
:return labeled_img: numpy.ndarray
:return eu_length_header: list
:return eu_length_data: list
"""
# Store debug
debug = params.debug
params.debug = None
x_list = []
y_list = []
segment_lengths = []
rand_color = color_palette(len(objects))
labeled_img = segmented_img.copy()
for i, cnt in enumerate(objects):
# Store coordinates for labels
x_list.append(objects[i][0][0][0])
y_list.append(objects[i][0][0][1])
# Draw segments one by one to group segment tips together
finding_tips_img = np.zeros(segmented_img.shape[:2], np.uint8)
# fig_name = (os.path.splitext(filename)[0] + '_pseudo_fvfm.png')
# plt.savefig(fig_name, dpi=600, bbox_inches='tight')
# plt.clf()
# analysis_images.append(['IMAGE', 'fvfm_pseudo', fig_name])
# path = os.path.dirname(filename)
# fig_name = 'FvFm_pseudocolor_colorbar.svg'
# if not os.path.isfile(os.path.join(path, fig_name)):
# plot_colorbar(path, fig_name, 2)
if params.debug == 'print':
print_image(fmin_mask, os.path.join(params.debug_outdir, str(params.device) + '_fmin_mask.png'))
print_image(fmax_mask, os.path.join(params.debug_outdir, str(params.device) + '_fmax_mask.png'))
print_image(fv, os.path.join(params.debug_outdir, str(params.device) + '_fv_convert.png'))
fvfm_hist_fig.save(os.path.join(params.debug_outdir, str(params.device) + '_fv_hist.png'))
elif params.debug == 'plot':
plot_image(fmin_mask, cmap='gray')
plot_image(fmax_mask, cmap='gray')
plot_image(fv, cmap='gray')
print(fvfm_hist_fig)
# Store into global measurements
if not 'fvfm' in outputs.measurements:
outputs.measurements['fvfm'] = {}
outputs.measurements['fvfm']['bin_number'] = bins
outputs.measurements['fvfm']['fvfm_bins'] = np.around(midpoints, decimals=len(str(bins))).tolist()
outputs.measurements['fvfm']['fvfm_hist'] = fvfm_hist.tolist()
outputs.measurements['fvfm']['fvfm_hist_peak'] = float(max_bin)
outputs.measurements['fvfm']['fvfm_median'] = float(np.around(fvfm_median, decimals=4))
outputs.measurements['fvfm']['fdark_passed_qc'] = qc_fdark
# Store images
# Create a plot reflecting new leaf objects to show how they got combined
rand_color = color_palette(len(new_leaf_obj))
labeled_img = cv2.cvtColor(plotting_img, cv2.COLOR_GRAY2RGB)
for i, cnt in enumerate(new_leaf_obj):
labeled_img = cv2.drawContours(labeled_img, cnt, -1, rand_color[i],
params.line_thickness, lineType=8)
# Reset debug mode
params.debug = debug
# Auto-increment device
params.device += 1
if params.debug == 'print':
print_image(labeled_img,
os.path.join(params.debug_outdir, str(params.device) + '_auto_combined_segments.png'))
elif params.debug == 'plot':
plot_image(labeled_img)
return labeled_img, new_leaf_obj