Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Matlab issue a warning when converting a double to a uint8 and vice versa?

Tags:

casting

matlab

Typically in Matlab colours are represented by three element vectors of RGB intensity values, with precision uint8 (range 0 - 255) or double (range 0 - 1). Matlabs functions such as imshow work with either representation making both easy to use in a program.

It is equally easy however to introduce a bug when assigning colour values from a matrix of one type, to that of another (because the value is converted silently, but not re-scaled to the new range). Having just spent a number of hours finding such a bug, I would like to make sure it is never introduced again.

How do I make Matlab display a warning when type conversion takes place?

Ideally it would only be when the conversion is between double and uint8. It should also be difficult to deactivate (i.e. the option is not reset when loading a workspace, or when matlab crashes).

like image 305
sebf Avatar asked Mar 16 '15 13:03

sebf


1 Answers

A possible solution is to define your own uint8 function that casts to uint8 and issues a warning if some value has been truncated.

You should place this function in a folder where it shadows the builtin uint8 funciton. For example, your user folder is a good choice, as it usually appears the first in path.

Or, as noted by Sam Roberts, if you want this function to be called only when converting from double into uint8 (not when converting from any other type into uint8), put it in a folder named @double within your path.

function y = uint8(x)
y = builtin('uint8', x);
if any(x(:)>255) || any(x(:)<0)
    warning('MATLAB:castTruncation', 'Values truncated during conversion to uint8')
end

The warning is on by default. You can switch it on or off with the commands warning('on','MATLAB:castTruncation') and warning('off','MATLAB:castTruncation') (thanks to CitizenInsane for the suggestion).

like image 120
Luis Mendo Avatar answered Oct 16 '22 12:10

Luis Mendo