There is no best code for Segmentation of Lungs from Chest X-Ray Images. The code depends on datasets or simmilar data types. The objectice of the code have to write the code, which may sutable for universal all images having simmilar types, though quite challenging, hence write the code which is best suitable for some wll verified public images multiple databases.
The segmentation approach is depends on test images, it would be better to comment more, if you can share a sample image. If the the ROI is distinctly differ from the rest part of the image, do threshold (recommended too, if it helps), otherwise with go with region growing or other segmentation methods and see theresults, you will be know which methods works for those images. There are so many approaches, request to follow the Gonzalez image processing using MATLAB book (Image Segmentation) for basic foundation.