Counting RNA-Seq Reads Into Genes With htseq-count
By the end of this guide you will have a gene-level count matrix with one row per gene and one column per sample. Values are integer counts, plus a set of summary rows that tell you whether the counting step worked. You need aligned reads in BAM format from a splice-aware aligner such as STAR or HISAT2. You also need the exact GTF annotation file that was used to build the aligner index, samtools, and either HTSeq 2.x via pip install HTSeq or Subread 2.x for featureCounts. Plan on 8 GB of RAM and a few minutes to a few hours per sample depending on depth and sort order. This guide covers measurement only. Interpreting expression changes in your own tissue in a clinical sense requires a physician, and nothing here is a diagnostic procedure.
1. Verify that your BAM and your GTF describe the same genome
The most common reason htseq-count returns zeros for every gene is a naming mismatch between the reference used for alignment and the annotation used for counting. Ensembl names chromosomes 1, 2, MT. UCSC and some GENCODE distributions name them chr1, chr2, chrM. The htseq-count tool does not warn loudly enough about this, so check it yourself.
samtools idxstats sample.bam | head -5
awk '$1 !~ /^#/ {print $1}' annotation.gtf | sort -u | head -5
If one side has chr and the other does not, fix the annotation rather than the BAM. Re-aligning is expensive and rewriting BAM headers invites subtler errors.
# Ensembl GTF -> UCSC-style names
awk 'BEGIN{OFS="\t"} /^#/{print; next} {$1="chr"$1; if($1=="chrMT") $1="chrM"; print}' \
Homo_sapiens.GRCh38.110.gtf > gencode_style.gtf
Also confirm the annotation release matches the assembly. A GRCh38 BAM counted against a GRCh37 GTF will produce plausible-looking but wrong numbers, because coordinates shift without any error being raised.
2. Determine library strandedness before you count anything
htseq-count defaults to -s yes, meaning it assumes the read maps to the same strand as the gene. Most modern kits (Illumina TruSeq Stranded mRNA and similar dUTP protocols) produce the opposite orientation, so the correct setting is -s reverse. Getting this wrong typically sends 60% to 95% of your reads into __no_feature and leaves you with a count matrix dominated by antisense noise.
Measure it rather than assume it. RSeQC gives a direct answer against a BED12 annotation:
infer_experiment.py -r gencode.v44.bed -i sample.bam -s 400000
A dUTP library reports most fragments as 1+-,1-+,2++,2--, which maps to -s reverse in htseq-count and -s 2 in featureCounts. An unstranded library splits roughly 50/50 between the two patterns, which maps to -s no and -s 0. You can cross-check with salmon quant -l A and read the inferred library type from lib_format_counts.json.
3. Sort the BAM the way you intend to count it
htseq-count accepts either name-sorted or position-sorted input, and the choice is a memory-versus-time tradeoff for paired-end data. With -r name, the tool requires that both mates of a pair appear in adjacent records, so it needs a name-sorted file and almost no memory. With -r pos, it buffers reads until it finds their mates.
We prefer name sorting for paired-end libraries. The sort costs a few minutes and removes an entire class of memory failures.
samtools sort -n -@ 8 -m 2G -o sample.namesorted.bam sample.bam
If you must count a position-sorted BAM, raise the buffer explicitly. The default is 30 million reads held in memory, and libraries with many orphaned mates or long-distance chimeras can exceed it.
htseq-count -r pos --max-reads-in-buffer 60000000 ...
Single-end data has no mate-pairing problem, so either order works.
4. Run htseq-count with the flags that change the answer
Here is the command we use for human paired-end stranded RNA-Seq against a GENCODE GTF:
htseq-count \
--format bam \
--order name \
--stranded reverse \
--type exon \
--idattr gene_id \
--additional-attr gene_name \
--mode union \
--nonunique none \
--secondary-alignments ignore \
--supplementary-alignments ignore \
-a 10 \
--nprocesses 4 \
--with-header \
--counts_output counts_raw.tsv \
sampleA.namesorted.bam sampleB.namesorted.bam sampleC.namesorted.bam \
gencode.v44.annotation.gtf
Four of these flags deserve explanation because they materially change the numbers.
--type exon --idattr gene_id tells htseq-count to union all exon features that share a gene_id and count fragments against that union. This is gene-level quantification, and it is what DESeq2 and edgeR expect. Counting at --type CDS excludes untranslated regions and will systematically lower counts for long-UTR genes.
--mode union counts a fragment for a gene if any of its aligned bases overlap that gene’s exon union. intersection-strict requires every base to fall inside one gene, and intersection-nonempty is a middle ground that resolves some reads spanning an exon boundary of a single gene. Union is the default and the right starting point. It is also the more forgiving mode for reads that extend slightly past annotated exon ends.
--nonunique none discards reads that align to more than one locus, and also reads that overlap two genes ambiguously. This is the conservative choice and we keep it. Paralog families and genes inside other genes will be undercounted as a result. The alternative --nonunique fraction splits a read equally among the features it hits, which is convenient but breaks the integer-count assumption behind negative binomial models.
-a 10 sets the minimum MAPQ. STAR assigns MAPQ 255 to uniquely mapped reads and 3 or 1 to multi-mappers, so this threshold quietly does most of the multi-mapper filtering before --nonunique ever sees them. If you switch aligners, re-examine this number, because MAPQ scales are not standardized across tools.
--nprocesses 4 parallelizes across input files. It does not parallelize within a file. Passing four BAMs with four processes gives near-linear speedup. Passing one BAM with four processes gives you nothing.
5. Read the summary lines before you read the genes
htseq-count appends five rows beginning with a double underscore. These are the diagnostic panel for the whole run, and they are the first thing to inspect.
grep '^__' counts_raw.tsv
For a good human polyA library aligned with STAR, we expect __no_feature under about 15% of assigned fragments and __ambiguous at a few percent. We expect __alignment_not_unique in the 5% to 20% range depending on how many multi-mapping loci the aligner reported. Values far outside those ranges point at a specific cause.
A __no_feature fraction above 50% almost always means the strandedness flag is wrong, and the fastest test is to re-run one sample with -s no on a subset of reads. If the unstranded count rises sharply, flip to -s reverse and re-run everything. A high __no_feature fraction that does not respond to strandedness suggests intronic or intergenic signal, which happens with total RNA or degraded input. An __ambiguous fraction above 10% usually means the annotation includes heavily overlapping gene models, and dropping to an Ensembl canonical or protein-coding-only GTF reduces it.
Then split the file into counts and summary for downstream use:
grep -v '^__' counts_raw.tsv > counts.tsv
6. Decide between htseq-count and featureCounts
They answer the same question with different engineering. htseq-count is Python, single-file-threaded, and processes roughly 1 to 5 million reads per minute. featureCounts is C and genuinely multithreaded. It typically finishes a 30 million fragment BAM in one to three minutes on eight cores. On the same annotation and equivalent settings, gene-level counts agree closely for the large majority of expressed genes, with disagreement concentrated in overlapping and multi-mapped loci.
We use featureCounts when throughput matters, and we use htseq-count when we want its exact overlap semantics or when a downstream pipeline was validated against it. The equivalent featureCounts command:
featureCounts -T 8 \
-p --countReadPairs \
-s 2 \
-t exon -g gene_id \
-Q 10 \
-a gencode.v44.annotation.gtf \
-o featurecounts.txt \
sampleA.bam sampleB.bam sampleC.bam
Note the -p --countReadPairs pair. Since Subread 2.0.2, -p only declares that the data is paired, and you must add --countReadPairs to count fragments rather than reads. Pipelines written before that change silently double their counts when run on a newer binary. featureCounts also has two practical advantages: it does not care about sort order, and column 6 of its output is the meta-feature length, which you need for TPM or for length-aware normalization.
One more cross-check is free. If you aligned with STAR, add --quantMode GeneCounts and it writes ReadsPerGene.out.tab with unstranded, forward, and reverse counts in columns 2, 3, and 4. Those columns approximate htseq-count in union mode, and comparing them is a fast way to confirm both your strandedness call and your counting setup. Large disagreement means one of the two runs used a different annotation.
7. Assemble the matrix and sanity-check it
With multiple BAMs on one command line, htseq-count 2.x already emits a matrix with one column per input file. Load it and check the basics before any statistics.
import pandas as pd
df = pd.read_csv("counts.tsv", sep="\t", index_col=0)
counts = df.drop(columns=["gene_name"], errors="ignore")
print(counts.sum()) # library sizes
print((counts.sum(axis=1) > 0).sum(), "genes detected")
print((counts.sum() / counts.sum().max()).round(2)) # relative depth
top = counts.div(counts.sum()).mean(axis=1).nlargest(10)
print(top)
Three checks catch most problems. Library sizes should land within a factor of about three of each other, and anything further off will dominate your dispersion estimates. Detected gene count for human whole blood or tissue is typically 13,000 to 18,000 genes with at least one count, and a number near 40,000 suggests you are counting noise across the full annotation. Finally, look at what the top ten genes are. Globin genes dominating a whole-blood sample is expected. Mitochondrial or ribosomal genes taking 40% of the library indicates degradation or a failed depletion step.
On depth: for gene-level differential expression in human tissue, 20 to 30 million assigned fragments per sample is the standard working range, and detection of moderately expressed genes is already good at 10 million. Splice-junction work, allele-specific expression, and low-abundance transcripts need 50 to 100 million or more. Adding replicates buys more statistical power than adding depth once you are past roughly 20 million fragments.
Feed the integer counts directly into DESeq2 or edgeR. Do not pre-normalize to CPM or TPM first, because both tools model counts and estimate their own size factors. Gene-level counts produced this way are the standard input for downstream network and pathway analysis of expression data 1, and the same count matrices are what multi-omics studies join against proteomic and metabolomic layers 23. Where you plan to combine your own RNA-Seq with public expression datasets, expect annotation version and platform differences to require explicit harmonization 4.
One caution specific to a single-person longitudinal profile. With one individual sampled over time, you have no biological replication across people, so a two-condition test is not available in the usual sense. What the data supports is tracking each gene against its own prior values and flagging large, sustained changes for follow-up. Any clinical reading of such a change belongs with a physician who can see the rest of your workup.
Common problems
Every gene has a count of zero and __no_feature holds nearly all reads. This is a chromosome naming or assembly mismatch. Compare samtools idxstats output against the first column of the GTF, as in step 1.
htseq-count errors out with a message about missing gene_id. You are using a GFF3 file rather than a GTF, and GFF3 attributes are ID and Parent instead. Either convert with gffread -T annotation.gff3 -o annotation.gtf or set --idattr to the attribute your file carries. NCBI RefSeq GFF3 files often need --idattr gene with --type exon.
Memory grows until the process is killed. You passed a position-sorted paired-end BAM with -r pos and a library containing many orphan mates. Name-sort the file and switch to -r name.
A warning appears about reads not being properly paired, followed by very low counts. The BAM was coordinate-sorted but declared as name-sorted, so mates never appear adjacent. Check the header with samtools view -H sample.bam | grep SO:.
Counts are exactly double what you expected from featureCounts. You used -p without --countReadPairs on Subread 2.0.2 or later, so reads were counted individually instead of as fragments.
All counts are near zero despite a high alignment rate. You aligned to a transcriptome rather than a genome, perhaps with Bowtie2 against a cDNA FASTA. htseq-count needs genome coordinates to compare against a GTF. Use salmon or kallisto for transcriptome alignments, or re-align to the genome with STAR.
3’ single-cell or single-nucleus data gives implausible gene-level values. Those protocols require UMI deduplication and cell-barcode handling, which htseq-count does not perform. Use the platform-appropriate counting tool instead.
Footnotes
-
Saleh A. Almatroodi, Tarique Sarwar, Arshad Husain Rahmani. Decoding Tumor–Immune Interactions in Hepatocellular Carcinoma Through Network-Centered Identification of CXCR2. International Journal of Molecular Sciences, 2026. https://doi.org/10.3390/ijms27167501 ↩
-
Eun Ki Min, Hyojin Lee, Eun Ji Sung, et al. Integrative multi-omics reveals analogous developmental neurotoxicity mechanisms between perfluorobutanesulfonic acid and perfluorooctanesulfonic acid in zebrafish. Journal of Hazardous Materials, 2023. https://doi.org/10.1016/j.jhazmat.2023.131714 ↩
-
Lei Wang, Lingran Wang, Chang Liu, et al. Multi-omics reveals the molecular mechanism of muscle quality changes in common carp (Cyprinus carpio) under two aquaculture systems. Comparative Biochemistry and Physiology Part D: Genomics and Proteomics, 2024. https://doi.org/10.1016/j.cbd.2024.101290 ↩
-
Pavithra Madamarandawala. Meta-Analysis of RNA-seq and Microarray Data. Next-Generation Sequencing, 2025. https://doi.org/10.1201/9781003354062-6 ↩
Pothos builds longitudinal molecular profiles of individuals: whole-genome sequencing, single-cell RNA sequencing, and plasma proteomics, delivered as a detailed report, every data file, and stored cells. Build your profile.